With the padding commented out as shown, the website works like I'd expect (2 div columns next to each other.
如图所示填充填充,网站就像我期望的那样(彼此相邻的2个div列)。
However, when I add padding, the #right div shifts downwards. How would I make it work as intended with padding?
但是,当我添加填充时,#right div向下移动。如何使用填充使其按预期工作?
HTML: Two divs contained directly in body
HTML:两个div直接包含在body中
CSS:
CSS:
#left {
background-color: green;
float: left;
margin-top: 0px;
width: 70%;
}
#right {
background-color: blue;
float: right;
margin-top: 0px;
width: 30%;
}
#left, #right {
//padding: 10px;
display: inline-block;
height: 800px;
}
3 个解决方案
#1
1
add
加
box-sizing: border-box;
box-sizing:border-box;
to your divs.
对你的divs。
If you don't the padding is added outside the div width (or height).. same as borders
如果不这样,填充将添加到div宽度(或高度)之外..与边框相同
Edited: and
编辑:和
-webkit-box-sizing: border-box; -moz-box-sizing: border-box;
-webkit-box-sizing:border-box; -moz-box-sizing:border-box;
for a bit more browser compatibility
获得更多浏览器兼容性
#2
0
if you are using css3 , you can use box-sizing: border-box;
如果您使用的是css3,则可以使用box-sizing:border-box;
else, you can have another child div
and apply padding
to the child div
instead of the parent div
否则,您可以使用另一个子div并将填充应用于子div而不是父div
#3
0
#left {
background-color: green;
float: left;
margin-top: 0px;
width: 70%;
}
#right {
background-color: blue;
float: right;
margin-top: 0px;
width: 30%;
}
#left, #right {
padding: 10px;
display: inline-block;
height: 800px;
color:#fff;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
<div id="left"> left </div>
<div id="right"> right </div>
#1
1
add
加
box-sizing: border-box;
box-sizing:border-box;
to your divs.
对你的divs。
If you don't the padding is added outside the div width (or height).. same as borders
如果不这样,填充将添加到div宽度(或高度)之外..与边框相同
Edited: and
编辑:和
-webkit-box-sizing: border-box; -moz-box-sizing: border-box;
-webkit-box-sizing:border-box; -moz-box-sizing:border-box;
for a bit more browser compatibility
获得更多浏览器兼容性
#2
0
if you are using css3 , you can use box-sizing: border-box;
如果您使用的是css3,则可以使用box-sizing:border-box;
else, you can have another child div
and apply padding
to the child div
instead of the parent div
否则,您可以使用另一个子div并将填充应用于子div而不是父div
#3
0
#left {
background-color: green;
float: left;
margin-top: 0px;
width: 70%;
}
#right {
background-color: blue;
float: right;
margin-top: 0px;
width: 30%;
}
#left, #right {
padding: 10px;
display: inline-block;
height: 800px;
color:#fff;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
<div id="left"> left </div>
<div id="right"> right </div>