垂直中心divs浮动

时间:2014-01-20 11:11:45

标签: html css

我在.container div中有两列:它们是percentage宽度并浮动left。我需要这些浮子的内容垂直和水平居中。它们是动态高度,可能会发生变化。我想避免使用jQuery。有人会知道一个简单的方法吗?

http://jsfiddle.net/LnMPC/2/

CSS:

.container {
    width: 600px;
    background-color: lightgrey;
    overflow: auto;
    height: 400px;
}
.col40 {
    width: 40%;
    height: 100%;
    float: left;
    background-color: green;
}
.col60 {
    width: 60%;
    float: left;
    background-color: blue;
    height: 100%;
}
p {
    width: 13em;
    background-color: salmon;
}

HTML:

<div class="container">
    <div class="col40">
        <p>40% -- Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet illo ab temporibus consequuntur excepturi sint delectus laboriosam aspernatur quas tenetur corporis error consequatur tempore eos minus asperiores voluptatum alias quibusdam!</p>
    </div>
    <div class="col60">
        <p>60% -- Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus vel dolorum. Quos atque deleniti fuga quo consequuntur molestias beatae voluptates magni architecto ducimus inventore exercitationem voluptatum nostrum. Labore culpa modi.</p>
    </div>
</div>

3 个答案:

答案 0 :(得分:1)

CSS

.container{
display:table;
}
.col40,.col60{
display:table-cell;
vertical-align:middle;
}
.col40{
width:40%;
}
.col60{
width:60%;
}

如果你想横向居中,它们已经达到了100%(40 + 60),所以我不能完全确定你在寻找什么。

答案 1 :(得分:1)

试试这个:

http://jsfiddle.net/LnMPC/5/

我想这就是你想要的,对吧?

p {
    width: 13em;
    background-color: salmon;
    margin: 0 auto;
    margin-top: 100px;
}

答案 2 :(得分:1)

display:table是避免float的新趋势,因为您稍后需要clear:)

working demo

<强> CSS

html, body {
    width: 100%;
    height: 100%;
    margin:0;
    padding:0;
}
.container {
    width: 600px;
    background-color: lightgrey;
    overflow: auto;
    height: 400px; /* or "100%" if container needs to be full-height*/
    display:table;        /* added*/
}
.col40 {
    width: 40%;
    height: 100%;
    background-color: green;
    display:table-cell;        /* added*/
    vertical-align:middle;        /* added*/
}
.col60 {
    width: 60%;
    background-color: blue;
    height: 100%;
    display:table-cell;        /* added*/
    vertical-align:middle;        /* added*/
}
p {
    width: 13em;
    margin:0 auto; /* added to center the content*/
    text-align:center;        /* added - optional */
    background-color: salmon;
}