css - Flexbox 将几个项目向左对齐,几个向中心对齐,几个向右对齐 - 顺序应该是可变的
问题描述
对于以下情况,我需要一个 CSS 解决方案:
我有几个孩子,比如说四个。并非所有四个孩子的宽度都相同。默认情况下,项目向左对齐。我使用margin-left
和/或margin-right
自动将项目对齐到中心/右侧。order
我使用 CSS属性更改项目的顺序。
现在我想将项目与容器的左侧、中心和右侧对齐。孩子的顺序应该在视口上改变(使用@media
查询)。
如何以不同的视口宽度将未指定数量的项目居中到左侧、中心和右侧?
我的(简化的)HTML
<div class="header-container">
<div class="first-child">
</div>
<div class="second-child">
</div>
<div class="third-child">
</div>
<div class="fourth-child">
</div>
</div>
我还将我的简化情况放在这个 JSFiddle中。
带有视口的外观的具体示例
@media (max-width: 799px) {*
left: first-child and second-child
center: third-child
right: fourth-child
}
@media (max-width: 800px) and (max-width: 1319px) {
left: third-child
center: first-child and second-child
right: fourth-child
}
@media (min-width: 1320px) {
left: first-child
center: third-child
right: second-child
fourth-child - display: none;
}
解决方案
首先,您必须将例如位于中间的孩子分组:
<div class="grouped-items">
<div class="second-child">
</div>
<div class="third-child">
</div>
</div>
之后,您将拥有三组项目或单独的项目。利用justify-content: space-between
它看起来像这样(在整页中打开以查看最佳结果):
.header-container {
width: 100%;
height: 68px;
background-color: white;
display: flex;
justify-content: space-between;
}
/* Set display: flex so they will act same as if they weren't in another div */
.grouped-items {
display: flex;
}
.first-child {
width: 60px;
height: 100%;
background-color: red;
}
.second-child {
width: 80px;
height: 100%;
background-color: green;
}
.third-child {
width: 50px;
height: 100%;
background-color: blue;
}
.fourth-child {
width: 100px;
height: 100%;
background-color: black;
}
@media (max-width: 799px) {
.grouped-items {
order: 1;
}
.third-child {
order: 2;
}
.fourth-child {
order: 3;
}
}
@media (min-width: 800px) and (max-width: 1319px) {
.grouped-items {
order: 2;
}
.third-child {
order: 1;
}
.fourth-child {
order: 3;
}
}
@media (min-width: 1320px) {
.fourth-child {
display: none;
}
.grouped-items {
order: 2;
}
.third-child {
order: 1;
}
}
body {
background-color: grey;
margin: 0;
}
<div class="header-container">
<div class="grouped-items">
<div class="first-child">
</div>
<div class="second-child">
</div>
</div>
<div class="third-child">
</div>
<div class="fourth-child">
</div>
</div>
要更改媒体上的顺序,只需使用order
推荐阅读
- r - 调用 .Call 的补丁函数
- php - 致命错误:无法声明类 ProductFilterIterator,因为该名称已在
- apache-kafka-streams - Kafka Streams API 如何从 Schema Registry 获取正确的模式?
- apollo - 使用 ApolloClient,无法将基本凭证添加到标头
- ruby-on-rails - 如何从 hash:Hashie::Mash 中检索值
- c - 使用 GIOChannel 和 GTK+ 从发送方获取 IP 地址
- python - TypeError:'numpy.float64'对象在第二次调用数组时不可调用
- arrays - 在 Delphi 中解析 Json 数组
- php - 我无法将照片发送到电报 api (400_Bad_Request)
- python - 尝试创建外键 sqlit3 p 时出现语法错误