Inside vs. Outside Borders
When styling an HTML element with a border, it's essential to consider where the border is positioned relative to the element's dimensions. By default, CSS borders are placed outside the element, adding width to both sides.
Maintaining Div Size with Box-Sizing
To ensure that a div's dimensions remain unchanged when a border is added, the box-sizing property comes into play. Setting it to border-box includes the border within the specified width and height of the element.
CSS Implementation
Here's a CSS example that demonstrates the effect of box-sizing:
div { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; width: 100px; height: 100px; border: 20px solid #f00; background: #00f; margin: 10px; }
In this example, the div has a border of 20px. Without box-sizing: border-box, the div would have a total width of 140px (100px for the content and 20px for the border on each side). However, with box-sizing: border-box, the border is included within the specified width of 100px, ensuring the div's actual width remains 100px.
The above is the detailed content of How Does `box-sizing: border-box` Affect the Size of an HTML Element with a Border?. For more information, please follow other related articles on the PHP Chinese website!