我有两个div, parent和child,我想让child的左边(left border)位于parent的中间。
为什么这个代码不能工作?即left: 50%
代表child,不工作。
<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%;
}
演示http://jsfiddle.net/vrse2/5/需要设置position
为absolute
或relative
:
#inner {
width: 400px;
height: 300px;
background-color: #090;
position: absolute;
left: 50%;
}
CSS left
仅适用于定位元素。
引自W3C
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%;
}
好读
- MDN: CSS Reference -left (Best IMHO)
- W3C: CSS/Properties/left
你需要添加position: absolute;
到你的CSS。left
用于绝对定位。
在你的例子中:
#inner {
width: 400px;
height: 300px;
background-color: #090;
position: absolute;
left: 50%;
}
使用说明:
margin-left: 50%;
或:
position:relative;
left:50%;
试试用以下:
HTML Part:
<div id="outher">
<div id="inner">
</div>
</div>
CSS Part:
#outher {
width: 1000px;
height: 1000px;
background-color: #ccc;
}
#inner {
width: 400px;
height: 300px;
background-color: #090;
left: 50%;
margin:0 auto;
position: absolute;
}
我想这也许能帮助你解决你的问题。