Home >Web Front-end >CSS Tutorial >How to Keep a Div's Dimensions Unchanged When Adding an Inner Border?

How to Keep a Div's Dimensions Unchanged When Adding an Inner Border?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 03:49:10167browse

How to Keep a Div's Dimensions Unchanged When Adding an Inner Border?

How to Position a Border Inside a Div Without Extending Its Dimensions?

When styling a

element with a border, the default behavior is to add the border thickness to both the width and height of the element. However, you may encounter scenarios where you want the border to appear within the existing dimensions of the div.

To achieve this effect, you can use the box-sizing property and set it to border-box:

div {
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  border: 20px solid #f00;
  background: #00f;
  margin: 10px;
}

By setting box-sizing to border-box, the width and height of the div will include the border thickness, ensuring that the visible box remains the same size while the border appears inside its edges:


<pre class="brush:php;toolbar:false">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;

}

div div {

box-sizing: border-box;
border: 10px solid red;

}


Hello!

Hello!

The above is the detailed content of How to Keep a Div's Dimensions Unchanged When Adding an Inner Border?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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