Div width percentage not working in CSS [duplicate]

大城市里の小女人 提交于 2019-12-12 04:58:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!