Home > Web Front-end > CSS Tutorial > How Does `box-sizing: border-box` Affect the Size of an HTML Element with a Border?

How Does `box-sizing: border-box` Affect the Size of an HTML Element with a Border?

Linda Hamilton
Release: 2024-12-15 02:05:19
Original
647 people have browsed it

How Does `box-sizing: border-box` Affect the Size of an HTML Element with a Border?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template