Css - Box Sizing
Css - Box Sizing
The CSS box-sizing property allows us to include the padding and border in an element's total
width and height.
This means: When you set the width/height of an element, the element often appears bigger
than you have set (because the element's border and padding are added to the element's
specified width/height).
The following illustration shows two <div> elements with the same specified width and height:
The two <div> elements above end up with different sizes in the result (because div2 has a
padding specified):
<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
width: 300px;
height: 100px;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
</style>
</head>
<body>
<h1>Without box-sizing</h1>
<br>
<div class="div2">This div is bigger (width is also 300px and height is 100px).</div>
</body>
</html>
If you set box-sizing: border-box; on an element, padding and border are included in the width
and height:
<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
width: 300px;
height: 100px;
box-sizing: border-box;
.div2 {
width: 300px;
height: 100px;
padding: 50px;
box-sizing: border-box;
</style>
</head>
<body>
<h1>With box-sizing</h1>
<br>
<div class="div2">Hooray!</div>
</body>
</html>
Since the result of using the box-sizing: border-box; is so much better, many developers want
all elements on their pages to work this way.
The code below ensures that all elements are sized in this more intuitive way. Many browsers
already use box-sizing: border-box; for many form elements (but not all - which is why inputs
and text areas look different at width: 100%;).
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
*{
box-sizing: border-box;
input, textarea {
width: 100%;
</style>
</head>
<body>
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
Comments:<br>
</textarea>
<br><br>
</form>
<p><strong>Tip:</strong> Try to remove the box-sizing property from the style element and look
what happens.
Notice that the width of input, textarea, and submit button will go outside of the screen.</p>
</body>
</html>