2016-03-11 38 views
1

如何對齊div以便兩個標籤具有相同的寬度並右對齊,並且兩個內容都在相同的位置開始。有些人建議float,但我不推薦浮動內容。有沒有這樣做的靈活方式。flex上的div文本對齊

enter image description here

<!DOCTYPE HTMML> 
<html> 
<body> 
    <div> 
     <div style="display: flex; flex-direction:row;"> 
      <div style="align: right; background: blue"> 
       Long label: 
      </div> 
      <div style="text-align: left; background: green"> 
       This is the content 
      </div> 
     </div> 

     <div style="display: flex; flex-direction:row;"> 
      <div style="align: right; background: blue"> 
       label: 
      </div> 
      <div style="text-align: left; background: green"> 
       This is the content 
      </div> 
     </div> 
    </div> 
</body> 
</html> 
+0

即使我給固定的寬度其不響應它。 – anivas

回答

1

使用柔性盒... ...除非您使用固定寬度值(無論它們是什麼)......否則非兄弟姐妹之間沒有寬度/高度均衡。

您需要給定其中一個元素的固定寬度值,然後讓其他元素用flex:1佔據剩餘空間。

.blue { 
 
    background: lightblue; 
 
    /* width: 150px; */ 
 
    flex: 0 0 150px 
 
} 
 
.green { 
 
    background: #bada55; 
 
    flex: 1; 
 
} 
 
.parent { 
 
    display: flex; 
 
}
<div class="parent"> 
 
    <div class="blue"> 
 
    Long label: 
 
    </div> 
 
    <div class="green"> 
 
    This is the content 
 
    </div> 
 
</div> 
 

 
<div class="parent"> 
 
    <div class="blue"> 
 
    label: 
 
    </div> 
 
    <div class="green"> 
 
    This is the content 
 
    </div> 
 
</div>

+0

這有助於感謝! – anivas

0

爲什麼不是一類簡單地添加到內容和標籤的div?

HTML

<div> 
<div> 
    <div class="label-div">Long label</div> 
    <div class="content-div">Content</div> 
</div> 
<div> 
    <div class="label-div">Label</div> 
    <div class="content-div">Content</div> 
</div> 
</div> 

CSS

.label-div { 
    width: 70px; 
    text-align: right; 
} 

.content-div { 
    text-align: left; 
} 

這樣,你可以肯定的是所有的標籤div的長度相等。