css“离开”不起作用

时间:2013-01-05 12:36:43

标签: html css positioning

我有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%;
}

demo http://jsfiddle.net/vrse2/5/

6 个答案:

答案 0 :(得分:25)

您需要将position设置为absoluterelative

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}

答案 1 :(得分:11)

CSS left仅适用于定位元素。

Quoted from 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

答案 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)

我可以补充一点,如果你没有左边的%,你的图像将继续堆叠,或者他们将使用原始图像边缘之间的左边间隙。这没有在上面指出,而且非常令人困惑。