多个div,一些是左,一些是右,都与CSS垂直对齐

时间:2013-01-18 19:21:08

标签: css3

对于容器中的任意数量的元素,最好的方法是将一些元素左对齐,一些元素向右对齐,同时垂直居中左右内容?

例如,给定此标记:

    <div class="action">
        <div class="message">This is our message</div>
        <div class="comment">Comments for the message</div>
        <div class="person">John Doe</div>
        <div class="date">01/18/2013</div>
        <div class="time">12:35 PM</div>
    </div>

当人物,日期和时间与左右内容垂直居中对齐时,消息和评论是否可以在动作容器中保持对齐?这可以在没有新标记和每个元素的任何内容长度的情况下完成吗?

感谢。

2 个答案:

答案 0 :(得分:2)

有些CSS可以解决问题。具有包含div位置:relative,并将子div向左或向右浮动。同时将文本居中对齐。

.container{
    position: relative;
}

.left{
    float: left;   
    width: 50%;
    background-color: Silver;
    text-align: center;
}

.right{
    float: right;
    width: 50%;
    background-color: Yellow;
    text-align: center;
}

Fiddle Example

答案 1 :(得分:0)

对现有标记进行 minimal 更改(引入两个div标记,每列一个),如果使用Munawwar's flex-helper,这将变得相当简单。

<强> HTML:

<div class="hbox flex">
    <div class="left vbox main-center">
        <div class="message">
            <p>This is our message.</p>
            <p>It spans many lines.</p>
            <p>Or rather, paragraphs.</p>
            <p>Additional waffle.</p>
            <p>Syrup, bacon, a banana.</p>
            <p>Tall glass of milk.</p>
        </div>
        <div class="comment">Comments for the message.</div>
    </div>
    <div class="right vbox main-center">
        <div class="person">John Doe</div>
        <div class="date">01/18/2013</div>
        <div class="time">12:35 PM</div>
    </div>
</div>

<强> CSS:

/*Example-specific CSS*/
/*left column*/
.left {
    width: 80%;
    background-color: Silver;
    text-align: center;
}
/*right column*/
.right {
    width: 20%;
    background-color: Yellow;
    text-align: center;
}
/*Minimal use of Munawwar's flex-helper*/
/* https://github.com/Munawwar/flex-helper */
/*Stack child items vertically*/
.vbox {
    display: flex;

    /*Align children vetically*/
    flex-direction: column;
    align-content: flex-start;

    /*Prevent extending beyond boundaries*/
    overflow: hidden;
}
/*Stack child items horizontally*/
.hbox {
    display: flex;

    /*Align children horizontally*/
    flex-direction: row;
    align-content: flex-start;

    /*Wrap items to next line on main-axis*/
    flex-wrap: wrap;

    /*Prevent extending beyond boundaries*/
    overflow: hidden;
}
/*Stretch item along parent's main-axis*/
.flex {
    flex: 1;
}
/*Stack child items to the main-axis center*/
.main-center {
    justify-content: center;
}

JSFiddle demo

没有华夫饼在这个答案的制作中受到伤害,虽然有些可能已被吃掉了。