我有2个div,父母和孩子,我希望孩子左侧(左边界)将在父母的中心。
为什么这段代码不起作用?对于孩子来说,left: 50%
不起作用。
<div id="outher">
<div id="inner">
</div>
</div>
的CSS:
#outher {
width: 1000px;
height: 1000px;
background-color: #ccc;
}
#inner {
width: 400px;
height: 300px;
background-color: #090;
left: 50%;
}
答案 0 :(得分:25)
您需要将position
设置为absolute
或relative
:
#inner {
width: 400px;
height: 300px;
background-color: #090;
position: absolute;
left: 50%;
}
答案 1 :(得分:11)
CSS left
仅适用于定位元素。
Values <length> | <percentage> | auto | inherit
Initial value auto
Applies to positioned elements
Inherited No
尝试
#inner {
width: 400px;
height: 300px;
background-color: #090;
position: absolute;
left: 50%;
}
好读
答案 2 :(得分:4)
您需要在CSS中添加position: absolute;
。 left
用于绝对定位。
在你的情况下:
#inner {
width: 400px;
height: 300px;
background-color: #090;
position: absolute;
left: 50%;
}
答案 3 :(得分:3)
使用:
margin-left: 50%;
或者:
position:relative;
left:50%;
答案 4 :(得分:2)
尝试使用以下内容:
HTML部分:
<div id="outher">
<div id="inner">
</div>
</div>
CSS部分:
#outher {
width: 1000px;
height: 1000px;
background-color: #ccc;
}
#inner {
width: 400px;
height: 300px;
background-color: #090;
left: 50%;
margin:0 auto;
position: absolute;
}
我认为这可以帮助您解决问题。
答案 5 :(得分:0)
我可以补充一点,如果你没有左边的%,你的图像将继续堆叠,或者他们将使用原始图像边缘之间的左边间隙。这没有在上面指出,而且非常令人困惑。