将响应div与容器内的右侧对齐

时间:2015-03-28 16:03:12

标签: html css responsive-design

我有一个父div和两个子div。我的目标是将一个div居中并将另一个div对齐,并使两个响应

在这种类型的设置中,我似乎无法找到将第二个对齐到右边的传统方法:

<div id="container">

    <div id="middle">Centered to middle</div>

    <div id="right">I want to be to the right</div>

</div>

CSS:

#container {
    position: relative;
    width: 100%;
}

#middle {
    margin: 0 auto;
    position: relative;
    width: 100%;
    max-width:150px;
    height:300px;
}

#right {
    max-width:150px;
    width:100%;
}

这是jsFiddle。我们如何破解这个难题?

2 个答案:

答案 0 :(得分:1)

  1. 设为inline-block,否则第二个div将始终位于第二行

  2. 降低width的百分比,使其成为33%

  3. 删除max-width

  4. &#13;
    &#13;
    #container {
        position: relative;
        width: 100%;
        text-align:middle;
    }
    div{
        display:inline-block;
    }
    #middle {
        background: #ddd;
        margin: 0 auto;
        position: relative;
        width: 100px;
        margin-left:40%;
        height:300px;
    }
    
    #right {
        background:yellow;
        width:33%;
    float:right;
    }
    &#13;
    <div id="container">
        
        <div id="middle">Centered to middle</div>
        
        <div id="right">I want to to be to the right</div>
        
    </div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

添加了一个伪元素作为左列,因此布局变为[left] + [middle] + [right]并为父级设置table,为子级设置table-cell

<强> JSFiddle Demo

&#13;
&#13;
#container {
    display: table;
    table-layout: fixed;
    width: 100%;
}
#container:before, #middle, #right {
    display: table-cell;
}
#container:before {
    content:"";
}
#middle {
    background: aqua;
    width: 50%;
}
#right {
    background: yellow;
}
&#13;
<div id="container">
    <div id="middle">Centered to middle</div>
    <div id="right">I want to to be to the right</div>
</div>
&#13;
&#13;
&#13;

使用flexbox还有另一种方法,可以找到 here