所以我或多或少都有这样的代码
<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但无法完成它。
答案 0 :(得分:3)
是的,这可以通过Flexbox实现 - 在.content和子div上设置高度(例如内容: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-flow
是flex-direction
和flex-wrap
的简写。
Flex-direction
设置方向 - 行,列,行 - 反向,列 - 反向。
Flex-wrap
包装灵活项目(或不包含)。默认情况下为nowrap
,演示使用wrap
,您也可以使用wrap-reverse
答案 1 :(得分:0)
您可以通过将标记修改为以下结构来实现此目的:
<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-layout
:https://www.w3schools.com/css/css_grid.asp
答案 2 :(得分:0)
您可以使用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;
}
答案 3 :(得分:0)
这个技巧怎么样?
.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>
答案 4 :(得分:0)
是的,你可以考虑下面的代码。
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;
}