对于布局,我需要在一个flex容器中有三个flex项(行(,并且我希望它们被对齐为space-between
。。。第一行将包含一些云标签,第二行是价格,第三行是阅读更多链接。
但在某些情况下,对于特定项目,只需要存在最后一行(Read more(。
因此,在这些情况下,为了统一起见,我希望"阅读更多"链接放在容器的底部;但space-between
对这种方法没有多大帮助。。。
当只有一个子项时,如何将回退justify-content
属性设置为end
?
.container {
background-color: #aaa;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-end;
height: 200px;
margin-bottom: 20px;
}
.tags {
display: flex;
}
.tags span {
background-color: #f0f;
padding: 10px;
margin: 0 0 0 10px;
}
.price {
display: flex;
background-color: #ff0;
padding: 10px;
font-size: 150%
}
.read-more {
display: flex;
background-color: #0ff;
padding: 10px;
}
<div class="container">
<div class="tags">
<span>tag 1</span><span>tag2</span><span>tag 3</span>
</div>
<div class="price">
$100
</div>
<div class="read-more">
<a href="#">Read more >></a>
</div>
</div>
<div class="container">
<div class="read-more">
<a href="#">Read more >></a>
</div>
</div>
如果您能够/愿意更改HTML代码中flex项的顺序,您可以在那里反转它们,并在容器上使用flex-direction: column-reverse;
。这样;阅读更多";元素是第一个柔性项目,由于容器底部的方向相反:
.container {
background-color: #aaa;
display: flex;
flex-direction: column-reverse;
justify-content: space-between;
align-items: flex-end;
height: 200px;
margin-bottom: 20px;
}
.tags {
display: flex;
}
.tags span {
background-color: #f0f;
padding: 10px;
margin: 0 0 0 10px;
}
.price {
display: flex;
background-color: #ff0;
padding: 10px;
font-size: 150%
}
.read-more {
display: flex;
background-color: #0ff;
padding: 10px;
}
<div class="container">
<div class="read-more">
<a href="#">Read more >></a>
</div>
<div class="price">
$100
</div>
<div class="tags">
<span>tag 1</span><span>tag2</span><span>tag 3</span>
</div>
</div>
<div class="container">
<div class="read-more">
<a href="#">Read more >></a>
</div>
</div>
您可以给容器一个position: relative;
标记、.read-more
类和:only-child
伪类。然后,当它是容器中唯一的子级时,它将向其添加属性position:absolute; bottom:0; right:0;
这会将其移动到容器的右下角。justify-content: end !important;
不会将容器移动到您想要的位置。
示例:
.container {
background-color: #aaa;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-end;
height: 200px;
margin-bottom: 20px;
position:relative;
}
.tags {
display: flex;
}
.tags span {
background-color: #f0f;
padding: 10px;
margin: 0 0 0 10px;
}
.price {
display: flex;
background-color: #ff0;
padding: 10px;
font-size: 150%
}
.read-more {
display: flex;
background-color: #0ff;
padding: 10px;
}
.read-more:only-child{
position:absolute;
bottom:0;
right:0;
}
<div class="container">
<div class="tags">
<span>tag 1</span><span>tag2</span><span>tag 3</span>
</div>
<div class="price">
$100
</div>
<div class="read-more">
<a href="#">Read more >></a>
</div>
</div>
<div class="container">
<div class="read-more">
<a href="#">Read more >></a>
</div>
</div>