簡體   English   中英

使用Flex左右對齊

[英]Aligning left right using Flex

所以我大概有這樣的代碼

<div class="content">
   <div class="c1">
   <div>
   <div class="c2">
   <div>
   <div class="c3">
   <div>
   <div class="c4">
   <div>
</div>

通過使用flex,我可以這樣做嗎?

<c1>         <c3>
<c2>         <c4>  

我知道我可以使用<ul><table> ,但是我只是想知道是否可以使用flex來做到這一點。 我嘗試使用flex但無法完成。

DEMO

是的,使用Flexbox可以實現-在.content和子div上設置高度(例如,content:100px,divs 50px),並指定flex-flow: column wrap

.content {
   display: flex;
   align-items: center;
   justify-content: center;
   flex-flow: column wrap;
   align-content: stretch;
   height: 100px;
}

.content div {
  height: 50px;
  width: 50px;
}

Flex-flowflex-directionflex-wrap簡寫。

Flex-direction設置方向-行,列,行反向,列反向。

Flex-wrap包裝(或不包裝)柔性物品。 默認情況下,這是nowrap ,演示使用wrap ,還可以使用wrap-reverse

您可以通過將標記修改為以下結構來實現此目的:

<div class="content">
   <div class="left-col">
       <div class="c1"><div>
       <div class="c2"><div>
   </div>
   <div class="right-col">
       <div class="c3"><div>
       <div class="c4"><div>
   </div>
</div>

現在您有兩列。 只需將以下樣式添加到CSS

.content {
    display: flex;
    justify-content: space-between; // or whatever you want
    flex-direction: row; // row is the default value, so you don't need to specify it. It will place the cols beside each other.
}

.left-col, .right-col {
    display: flex;
    flex-direction: column;
}

通過指定flex-direction: column; 元素將位於彼此下方。

這是一些很棒的資源: https : //css-tricks.com/snippets/css/a-guide-to-flexbox/

也許您還想查看新的本機grid-layouthttps : //www.w3schools.com/css/css_grid.asp

您可以使用CSS網格輕松完成此操作,我認為這更有用,但這是使用CSS網格的代碼

HTML

<div class="content">
    <div class="c1">test 1</div>
    <div class="c2">test 2</div>
    <div class="c3">test 3</div>
    <div class="c4">test 4</div>
</div>

CSS:

.content {
    display: grid;
    grid-template-columns: 1fr 1fr;
}

那把戲呢?

 .content { display: flex; flex-direction: column; height: 50px; flex-wrap: wrap; } 
 <div class="content"> <div class="c1">1</div> <div class="c2">2</div> <div class="c3">3</div> <div class="c4">4</div> </div> 

是的,您可以這樣做,請考慮以下代碼。
HTML

 <div class="content ">  
      <div class="col-12 d-flex justify-content-between">
       <div class="c1 col-6 text-center">c1
       </div>
       <div class="c2 col-6 text-center">c2
       </div>
     </div>
     <div class="col-12 d-flex justify-content-between">
       <div class="c3 col-6 text-center">c3
       </div>
       <div class="c4 col-6 text-center">c4
       </div>
         </div>
    </div>

CSS

.justify-content-around {
    -ms-flex-pack: distribute!important;
    justify-content: space-around!important;
}
.d-flex {
    display: -webkit-box!important;
    display: -ms-flexbox!important;
    display: flex!important;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM