I am creating a site with DIV
s. Everything's working out except when I create a DIV. I create them like this (example):
newdiv {
width: 200px;
height: 60px;
padding-left: 20px;
text-align: left;
}
When I add the padding-left
property, the width of the DIV
changes to 220px, and I want it to remain at 200px.
Let's say I create another DIV
named anotherdiv
exactly the same as newdiv
, and put it inside of newdiv
but newdiv
has no padding and anotherdiv
has padding-left: 20px
. I get the same thing, newdiv
's width will be 220px.
How can I fix this problem?
Put a div in your newdiv with width: auto
and margin-left: 20px
Remove the padding from newdiv.
Try this
box-sizing: border-box;
Add property:
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
Note: This won't work in Internet Explorer below version 8.
when I add the padding-left property, the width of the DIV changes to 220px
Yes, that is exactly according to the standards. That's how it's supposed to work.
Let's say I create another DIV named anotherdiv exactly the same as newdiv, and put it inside of newdiv but newdiv has no padding and anotherdiv has padding-left: 20px. I get the same thing, newdiv's width will be 220px;
No, newdiv will remain 200px wide.
If you would like to indent text within a div without changing the size of the div use the CSS text-indent
instead of padding-left
.
.indent {_x000D_
text-indent: 1em;_x000D_
}_x000D_
.border {_x000D_
border-style: solid;_x000D_
}
_x000D_
<div class="border">_x000D_
Non indented_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="border indent">_x000D_
Indented_x000D_
</div>
_x000D_
just change your div width to 160px if you have a padding of 20px it adds 40px extra to the width of your div so you need to subtract 40px from the width in order to keep your div looking normal and not distorted with extra width on it and your text all messed up.
simply add box-sizing: border-box;
Source: Stackoverflow.com