2013-01-18 72 views
1

給定容器中任意數量的元素,將一些元素對齊到左側和一些右側,同時將左側和右側對齊正確的內容垂直?多個div,一些左邊,一些右邊,所有與CSS垂直對齊

例如,假設此標記:

<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

一些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

+0

但是,如果有多個左側div和多個右側div,則右側div將與最後一個左側div內聯。而且,這不是垂直居中。對? – James

+0

爲了確保我理解,您希望兩列的高度相同(等於最高的列),並且較短的列要垂直居中? –

+0

正確。無論任何div的內容長度或任何一邊有多少個div,較短的列應垂直居中到較長的列的內容,並且兩列應垂直居中到容器。謝謝。 – James

0

隨着最小改變現有的標記(推出兩款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

沒有鬆餅受到侵害生產這個答案的,雖然有些可能已經被吃掉了。

相關問題