Div Width Percentage Not Working In Css
Solution 1:
This is because of the borders. If you leave out the borders your div will align. Using the border-box solves the problem:
.leftdiv{
box-sizing: border-box;
width:20%;
border:2px solid blue;
float:left;}
.middlediv{
box-sizing: border-box;
width:60%;
border:1px solid orange;
float:left;}
.rightdiv{
box-sizing: border-box;
width:20%;
border:1px solid black;
float:right;}
The idea of a box-sizing: border box is that it modfies the behaviour of the normal box model to treat the padding and border as a part of the width element. So now when you set the % width the border is already taken into account. This is why now the 20+20+60 amount to 100%.
Additional info can be found in this link
Solution 2:
The issue is that padding and border are, by default, calculated in addition to the width, not included in the width value. You need to use the box-sizing: border-box override to have them included:
div {
box-sizing: border-box;
}
Or, preferable, add it to each individual div's style block (because you might not want to blanket apply it to all divs on the page).
.leftdiv,.middlediv,.rightdiv{
box-sizing: border-box;
}
Example: https://codepen.io/anon/pen/RLZWWO
Solution 3:
The border takes up additional space that is not accounted for in the div width. Try adding box-sizing: border-box;
to each of your div classes.
Solution 4:
You should add this:
html, body {
margin: 0;
}
to reset the default margin of the all-wrapping body
and html
element to zero
and
* {
box.sizing: border-box;
}
to include padding and borders in your percentage values.
html,
body {
margin: 0;
}
* {
box-sizing: border-box;
}
.leftdiv {
width: 20%;
border: 2px solid blue;
float: left;
}
.middlediv {
width: 60%;
border: 1px solid orange;
float: left;
}
.rightdiv {
width: 20%;
border: 1px solid black;
float: right;
}
<body><divclass="leftdiv">left</div><divclass="middlediv">middle</div><divclass="rightdiv">right</div></body>
Post a Comment for "Div Width Percentage Not Working In Css"