为什么CSS浮动离开不能将两个div放在同一行?

时间:2016-02-19 14:51:39

标签: html css

我想用CSS在同一行上制作两个div。

enter image description here

body {
  margin: 0px;
  padding: 0px;
}
div {
  border: 1px solid black;
  font-size: 30px;
}
#wrapper {
  width: 900px;
  margin: 0px auto;
}
#header {
  width: 100%;
  height: 100px;
  background: red;
}
#main {
  width: 100%;
  height: 100px;
  background: blue;
}
#login_left {
  width: 50%;
  height: 100px;
  background: blue;
  float: left;
}
#login_right {
  width: 50%;
  height: 100px;
  background: yellow;
  float: left;
}
#footer {
  width: 100%;
  height: 50px;
  background: white;
}
<div id="wrapper">
  <div id="header">this is the top
  </div>
  <div id="main">
    <div id="login_left">login_left
    </div>
    <div id="login_right">login_right
    </div>
  </div>
  <div id="footer">this is the footer
  </div>
</div>

login_left和login_right都设置为float:左边的css和宽度是50%,为什么不能将两个login_left和login_right放在同一行?

我在Firefox中获得的css是以下内容。

  1. 为什么蓝色div满900 px?
  2. 为什么黄色div没有设置在右边?
  3. enter image description here

4 个答案:

答案 0 :(得分:8)

  1. 您使用边框,因此div为50%+ 2px(以修复使用box-sizing: border-box;
  2. login_left是50%(+ 2px)宽,所有行都是蓝色的事实是因为#main有蓝色背景

答案 1 :(得分:2)

{{ post_body | raw }}

DEMO

问题在于边界。它使用额外的2像素。

答案 2 :(得分:1)

<html>
<header>
<style type="text/css">
body{
      margin:0px;
      padding:0px;}
div{
    border:1px solid black;
    font-size:30px;
    box-sizing:border-box;}
#wrapper{
    width:900px;
    margin:0px auto;}
#header{
    width:100%;
    height:100px;
    background:red;}
#main{
    width:100%;
    height:100px;
    background:blue;}
#login_left{
    width:50%;
    height:100px;
    background:blue;
    float:left;
    }   
#login_right{
    width:50%;
    height:100px;
    background:yellow;
    float:left;
    } 
#footer{
    width:100%;
    height:50px;
    background:white;
    display:table;
    } 
</style>
</header>

<body>
<div id="wrapper">
    <div id="header">this is the top
    </div>
    <div id="main">
        <div id="login_left">login_left
        </div>
        <div id="login_right" >login_right
        </div>       
    </div>
    <div id="footer">this is the footer
    </div>
</div>
</body>
</html>

添加到您的代码: 对{div}选择器box-sizing:border-box;。可以将其视为内部边界而不是外部边界。它不会使用此属性为元素添加任何整体大小。当你使用50%和50%时,向所有方面添加1px意味着你超过100%,使你的div堆叠。

display:table;到页脚,使其显示在表格布局中,并尊重边框大小以匹配其他表格。

答案 3 :(得分:1)

删除边框使其有效:

fiddle

div{
    font-size:30px;
}

如果你想让他们跟随其他答案:

div{
   box-sizing:border-box; //ADD THIS
   border:1px solid black;
   font-size:30px;
}
相关问题