Box Sizing
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <h1>Box-sizing</h1> <div id="content-box"> <p>This is the default box-sizing of content-box</p> </div> <div id="no-box-sizing"> <p>This has no box-sizing property and is the same as the previous example</p> </div> <div id="border-box"> <p>This is box-sizing of border-box</p> </div> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
p { color: white; } div { width: 150px; height: 150px; } #content-box { background-color: blue; box-sizing: content-box; padding: 10px; } #no-box-sizing { background-color: red; padding: 10px; } #border-box { background-color: green; box-sizing: border-box; padding: 10px; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
box-sizing
box-sizing
is a CSS property that determines how the size of an element is calculated. By default,
the
size of an element is calculated based on its content, padding, and border, but with box-sizing
,
you can
change this behavior to include or exclude the element's padding and border from the calculation.
There are two values for the box-sizing
property:
content-box
: This is the default value. With content-box, the width and height of an element are calculated based on its content, padding, and border. In other words, the element's padding and border are added to the specified width and height.border-box
: With border-box, the width and height of an element are calculated based on its content only. The element's padding and border are included in the specified width and height, so the total size of the element remains constant.
box-sizing
is a useful property because it helps ensure consistent sizing and layout of elements
in your
web page.
Experiment with the Code
- Try setting the default
box-sizing
for the page toborder-box
using the universal selector.
Video and Code References
Questions? Subscribe and ask in the video comments: