CSS "left"不起作用



我有两个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/

需要设置positionabsoluterelative:

#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%;
}

好读

  1. MDN: CSS Reference -left (Best IMHO)
  2. 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;
}

我想这也许能帮助你解决你的问题。

最新更新