如何开始一个新行并将换行符与 Flexbox 中的另一个项目对齐?
我有一个弹性盒子,里面有不同的物品。
当它换行到新行时,我想将此新行与弹性盒第一行的第二项对齐,但我不知道如何执行此操作。元素的宽度将根据内部文本而动态变化。
div {
font-family: arial, sans-serif;
margin: 5px;
color: white;
border: 1px dotted black;
}
.parent {
display: flex;
flex-wrap: wrap;
width: 300px;
}
.unique_element {
background-color: Crimson;
width: 30%;
padding: 10px 10px 10px 10px;
}
.child {
background-color: CornflowerBlue;
padding: 10px 10px 10px 10px;
}
<div class="parent">
<div class="unique_element">First</div>
<div class="child">Second</div>
<div class="child">Third</div>
<div class="child">Fourth</div>
<div class="child">Fifth</div>
</div>
I have a flexbox with different items inside.
When it wraps onto a new line I want to align this new line with the 2nd item on the first row of the flexbox, but I can't figure out how to do this. The width of the elements will be dynamic, based on the text inside.
div {
font-family: arial, sans-serif;
margin: 5px;
color: white;
border: 1px dotted black;
}
.parent {
display: flex;
flex-wrap: wrap;
width: 300px;
}
.unique_element {
background-color: Crimson;
width: 30%;
padding: 10px 10px 10px 10px;
}
.child {
background-color: CornflowerBlue;
padding: 10px 10px 10px 10px;
}
<div class="parent">
<div class="unique_element">First</div>
<div class="child">Second</div>
<div class="child">Third</div>
<div class="child">Fourth</div>
<div class="child">Fifth</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因此,真正的问题是:在发生换行时如何重新排列 Flex 项目?
由于 HTML 和 CSS 本身具有 没有元素何时换行的概念,他们无法控制这种情况。您必须使用媒体查询或 JavaScript 来处理它。
选择检测换行的方法后,您可以使用
order
属性重新排列项目。So, the real question is: How to re-arrange flex items when wrapping occurs?
Since HTML and CSS, by themselves, have no concept of when elements wrap, they have no control of this situation. You have to handle it, either with media queries or JavaScript.
Once you've selected your method for detecting the wrap, you can use the
order
property to re-arrange the items.扩展@MichaelBenjamin 的精彩答案:
您可以通过设置新的父元素并将唯一元素嵌套为第一个子元素来解决此问题。将这个新的
master-parent
设置为display: flex;
。To expand on @MichaelBenjamin's fantastic answer:
You can work around this by setting a new parent element and nest the unique element as the first child. Set this new
master-parent
todisplay: flex;
.您可以在父 div 内创建两个 div,一个包含唯一元素,另一个包含通用子元素。这就是如何获得
如图所示的 CSS 分离样式。注意 .unique-wrapper 有 flex: 3 因为你将元素的宽度设置为 30%。
如果您想使用代码,这是我的codepen。
You can create two divs inside the parent div, one that holds the unique element and one that holds generic children. That's how you get the separation
Style the CSS as shown. Note .unique-wrapper has flex: 3 because you set the width of the element as 30%.
Here is my codepen if you want to play with the code.
创建一个用于间距的虚拟元素
create a dummy element for spacing