我正试图让两个并排的盒子占据屏幕的整个宽度.但是,当将宽度设置为50%时,每个盒子要扩展大约10px,宽度大于50%.我究竟做错了什么?
#sides {
padding-top: 40px;
padding-bottom: 40px;
background-color: white;
}
#leftside {
width: 50%;
background-color: grey;
padding: 20px;
margin: 0px;
position: relative;
}
#rightside {
width: 50%;
display: inline-table;
background-color: #018DCA;
float: left;
padding: 20px;
margin-left: 50%;
position: relative;
}
Run Code Online (Sandbox Code Playgroud)
...
<div id="sides">
<div id="leftside">
<h1>text</h1>
<p>
<h2>text</h2>
<br>
</div>
<div id="rightside">
<h1>text</h1>
<p>
<h2>text</h2>
<br>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
box-sizing: border-box;无论填充和边框大小如何,都需要浮动并确保您使用以确保宽度为50%.
您不需要使用float(实际上它不是用于整体文档布局的正确工具;它更适用于在不破坏文档流的情况下使用图像分解文本).
您可以通过使用display: inline-block;和注释左右之间的空白来减少CSS <div>.的jsfiddle
html, body {
margin: 0;
}
#sides {
padding-top: 40px;
padding-bottom: 40px;
background-color: white;
}
#leftside {
width: 50%;
background-color: grey;
padding: 20px 0;
display: inline-block;
}
#rightside {
width: 50%;
display: inline-block;
background-color: #018DCA;
padding: 20px 0;
}Run Code Online (Sandbox Code Playgroud)
<div id="sides">
<div id="leftside">
<h1>text</h1>
<p>
<h2>text</h2>
<br>
</div><!--
--><div id="rightside">
<h1>text</h1>
<p>
<h2>text</h2>
<br>
</div>
</div>Run Code Online (Sandbox Code Playgroud)