问题
Here is my CSS:
.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;
}
Here is my html:
<body>
<div class="leftdiv">left</div>
<div class="middlediv">middle</div>
<div class="rightdiv">right</div>
</body>
What I expect to see is three divs across the screen taking up 100% of the screen width.
Instead see this:
The right div is on the next line.
回答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
回答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
回答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.
回答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>
<div class="leftdiv">left</div>
<div class="middlediv">middle</div>
<div class="rightdiv">right</div>
</body>
来源:https://stackoverflow.com/questions/46507833/div-width-percentage-not-working-in-css