1

我有一个场景,我有一个 940 像素宽度的框,最多有 4 个 140 像素的子 div,它们之间有 20 像素,漂浮在一条线上。当有 1、2、3 或 4 个子 div 时,我希望 CSS 强制子 div 组居中。目前,当第 4 个被移除时,前 3 个的位置不会改变。

我正在使用 LESS。

我的代码:

#parent
{
    position: relative;
    width: 940px;
    clear: both;
    background-image: url(../images/bg.png);
    background-repeat: repeat-x;
    height: 100px;
    margin: 0 auto;
    margin-top: 2px;
}

#parent h1
{
    position: absolute;
    color: white;
    font-size: 36px;
    font-weight: 400;
    margin: 0;
    padding: 0;
    left: 5px;
    top: -24px;
}

#children
{
    position: relative;
    margin: 0 auto;
    margin-top: 35px;
}

.child
{
    width: 140px;
    padding-right:20px;
    float: left;
    text-align: center;   
}

#children:last-child
{
    padding-right: 0px;
    clear: right;
}

编辑:HTML ......

<div id="parent">

    <h1>Lorem Ipsum</h1>

    <div id="children">

        <div class="child" id="1"></div>
        <div class="child" id="2"></div>
        <div class="child" id="3"></div>
        <div class="child" id="4"></div>

     </div>

 </div>

此外,#children:last-child 似乎什么也没做。我假设它的规则应该适用于#4 是否正确?

4

2 回答 2

2

只需将 div #children 的宽度设置为 100% 和 text-align:center,这样它的 CSS 就变成了这样:

#children
{
    position: relative;
    margin: 0 auto;
    margin-top: 35px;
    width: 100%;
    text-align: center;
}

对于子元素,您必须删除 float 属性并给它们一个相对位置:

.child
{
    width: 140px;
    padding-right:20px;
    text-align: center;   
    position: relative;
}

它应该有效。如果您通过它的 id 清楚地指定最后一个子选择器,它也是首选, :last-child 不会在 IE7 或 IE6 上工作:

#4.child{
    padding-right: 0px;
    clear: right;
}

我认为你不应该以数字开头任何 id,id="1" | id="2" 等。它的语法不正确。

于 2012-09-08T00:37:37.217 回答
1

这是一个可以正常工作的jsfiddle:

http://jsfiddle.net/emYfz/

#children {
  width: 100%;
  text-align: center    
}

.child {
 display: inline-block;
 width: 140px;
 height: 20px;
 margin: 5px;
 background: #f00;
}
于 2012-09-08T00:44:12.287 回答