我正在尝试实现下一个设计,其中元素在换行之前占据所有可用空间,并保持文本居中:
现在我在容器中使用这些样式:
display: flex;
justify-content: center;
flex-wrap: wrap;
但我得到这个结果:
我使用一个简单的容器,里面有div,每个div都有一个span和anchor元素,如下所示:
没有应用任何额外的样式
确保链接具有下一个 CSS 属性:
overflow-wrap: break-word;
您还没有分享完整的 HTML 和 CSS,所以我只能通过添加我自己的示例来回答您的问题。请注意,当您以文本形式发布代码而不使用图像时,读者会更容易。
问题似乎是您没有从第一行的开头开始,而是将内容居中,并且项目无法增长足够(由于标准的 flex-grow 行为,不要占用所有可用空间):
<div class="container">
<div class="item"><span>Item 1</span><a href="#">Link</a></div>
<div class="item"><span>Item 2</span><a href="#">Link</a></div>
<div class="item"><span>Item 3</span><a href="#">Link</a></div>
<!-- .... -->
</div>
.container {
display: flex;
flex-wrap: wrap;
justify-content: start; /* align items to the start of the line */
gap: 10px; /* spacing between items */
}
.item {
margin: 5px;
flex-grow: 1; /* allows items to grow and take up any available space */
text-align: center; /* centers text within each item */
}
/* Minimum space around the container (optional) */
.container {
padding: 10px;
}
要在 Flex 项目之间添加视觉分隔符(例如管道 (|)),可以使用 CSS 中的 ::after 伪元素。这种方法允许您在除最后一项之外的每一项之后插入内容,这是此类分隔符的常见要求。
.item::after {
content: "|";
position: absolute;
right: -10px; /* specific spacing and styling needs */
top: 50%; /* Aligns with the middle of the item */
transform: translateY(-50%); /* centered vertically */
color: #ccc; /* Optional: sets the color of the separator */
}
.item:last-child::after {
content: none; /* Removes the separator from the last item */
}