box-sizing
As a default setting, width
and height
are calculated from one edge to the other edge of content (Content Box), but you can change the setting to "to the edge of borders" (Border Box) using the box-sizing
property.
The box-sizing property
There are two major box-sizing
property values:
content-box
: width and height are calculated based on the content box (edges of the content area).border-box
: width and height are calculated based on the border box (outer edges of borders).
Width: 100% problem
In website layout design, you may want to set width: 100%
to try to align a child element's width to its parent's. However, this may not work properly. As the default value of the box-sizing
property is content-box
, to calculate the total width, besides the width of the content area, you need to also take into account the width of the borders and paddings of the element.
If you set the width
of the child element to 100%
, the parent element cannot properly contain the child element as shown in the illustration below.
When you change the box-sizing
property to border-box
, the parent element can properly contain the child element as in the illustration below.
Practice
Objective:
Check how the box-sizing property works
1. Update the body section of the HTML file
Add the code below to the chapter10.html file. We are creating sets of parent and child elements with element design examples first.
<h2>Box Sizing</h2>
<h3>Box Examples</h3>
<div class="box-sizing-parent" style="width: 100px; height: auto; padding: 5px; margin: 5px;">div Parent</div>
<div class="box-sizing-child" style="width: 100px; height: auto; padding: 5px; margin: 5px;">div Child</div>
<h3>Original Box Sizing</h3>
<div class="box-sizing-parent">
<div class="box-sizing-child"></div>
</div>
<h3>Content Box</h3>
<div class="box-sizing-parent">
<div class="box-sizing-child" style="box-sizing: content-box;"></div>
</div>
<h3>Border Box</h3>
<div class="box-sizing-parent">
<div class="box-sizing-child" style="box-sizing: border-box;"></div>
</div>
2. Add CSS to the child elements
Open the practice.css and add new code to add color and margin to each HTML element.
We haven't explained the background-color
and border
properties yet. For now, just copy and paste the code into your file.
.box-sizing-parent{
background-color: #55D0DC;
margin:20px;
width:300px;
height:50px;
border:5px dotted #26BCCE;
padding:10px;
}
.box-sizing-child{
background-color: #E0F7F9;
border-style: solid;
border-color:#B3EBEF;
border-width:5px;
padding:10px;
width:100%;
}
3. Check the result with a browser
- Open chapter10.html with a browser.
- You can see how the
box-sizing
property works:- The default setting is
content-box
but it will result in an overflow of the child element. - By changing the property to
border-box
, the parent element can properly contain the child element.
- The default setting is
You can also check the sample result here (Demo Site).