CSS box-sizing Property
The CSS box-sizing property specifies how the total width and height of an element is calculated. By default, the width and height you set on an element only applies to the content area. With box-sizing, you can change that.
selector { box-sizing: value; }
- value – Defines the box-sizing model to use.
content-box
- content-box is the default value for the box-sizing property.
- It means the width and height properties apply only to the content area of the element. Padding and borders are added outside the content area, affecting the element's total size.
border-box
- border-box includes the content, padding, and border within the specified width and height of the element.
- This makes it easier to manage the layout, as the padding and border will not increase the element’s size beyond the set width and height.
Example: Default box-sizing
<!DOCTYPE html> <html lang="en"> <head> <style> div { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black; } </style> </head> <body> <div>This div has a width of 200px, and the padding and border are included inside that width.</div> </body> </html>
Global box-sizing
You can apply box-sizing: border-box; globally to all elements in your CSS by using the * universal selector.
Example
<!DOCTYPE html> <html lang="en"> <head> <style> *, *::before, *::after { box-sizing: border-box; } .container { width: 100%; padding: 20px; background-color: lightgray; } .box { width: 50%; /* This box will take 50% of the parent width */ padding: 20px; border: 2px solid black; background-color: lightblue; } </style> </head> <body> <div class="container"> <div class="box">This box will have a width of 50% of the container, with padding and border included inside the width.</div> </div> </body> </html>
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.