我正在开发一个导航栏,其中有 2 个元素。左边的标志,右边的动作列表(这个元素有一个动态数量的元素)。
当他们可以排成一排时,我希望他们这样做。
但是,当它们不再适合 1 行时,我希望将它们放在不同的行中,然后居中。像这样:
.container {
display: flex;
justify-content: space-between;
flex-flow: wrap;
width: 100%;
border: 1px solid #ddd;
}
.logo {
background-color: red;
}
.actions {
display: flex;
background-color: yellow
}
<div class="container">
<div class="logo">logo</div>
<div class="actions">
<div class="action-1">action 1</div>
<div class="action-2">action 2</div>
</div>
</div>
这可能吗?如果是这样,它会使用 grid 还是 flexbox?
要实现这个行为,你可以添加一个媒体查询,当屏幕宽度小于某个值时,将容器的 flex-direction 属性更改为 column。以下是如何修改代码的示例:
.container {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
border: 1px solid #ddd;
}
.logo {
background-color: red;
}
.actions {
display: flex;
background-color: yellow;
align-items: center; /* center items vertically */
}
@media (max-width: 768px) { /* adjust breakpoint value as needed */
.container {
flex-direction: column; /* switch to column layout when screen is narrow */
align-items: center; /* center items horizontally */
}
.actions {
margin-top: 10px; /* add some spacing between logo and actions */
}
}
本例中,当屏幕宽度小于768像素时,媒体查询将容器的flex-direction设置为column,并水平居中对齐项目。它还通过在 actions 元素上设置 margin-top 来在 logo 和 actions 之间增加一些间距。您可以根据设计需要调整断点值和间距。
评论更新:
.container {
display: flex;
justify-content: space-between;
align-items: center; /* center items vertically */
border: 1px solid #ddd;
}
.logo {
background-color: red;
}
.actions {
display: flex;
flex-grow: 1; /* allow container to grow to fill remaining space */
flex-shrink: 1; /* allow container to shrink if necessary */
flex-wrap: wrap; /* allow elements to wrap to a new line */
align-items: center; /* center items vertically */
justify-content: flex-end; /* align items to the right */
gap: 10px; /* add some spacing between action items */
}
.action {
padding: 5px 10px; /* add some padding to action items */
background-color: yellow;
white-space: nowrap; /* prevent text from wrapping */
}
.action:hover {
background-color: #ffcc00;
}
在这个例子中,
.actions
容器有flex-grow: 1
和flex-shrink: 1
,这允许它根据需要增长或收缩以填充容器中的剩余空间。当容器的宽度不足以容纳一行中的所有元素时,它们将换行,但仅作为最后的手段。 justify-content: flex-end
属性将元素右对齐,因此徽标保持在左侧。
您可以根据需要调整
gap
和padding
值以匹配您的设计,并为.action
项目添加任何悬停样式。