[英]Align 2 elements underneath each other without using flex-col
I have a simple html div:我有一个简单的 html div:
<div class="container">
<div class="icon1">+</div>
<span>Label</span>
<span>Context</span>
<div class="icon2">X</div>
</div>
.container {
display: flex;
width: 500px;
}
.icon1, .icon2 {
background: red;
border-radius: 50%;
padding: 8px;
color: #fff;
}
.icon2 {
margin-left: auto;
}
I want to align the span elements underneath each other but I don't want to add extra html elements and I need the icons to align left and right.我想将 span 元素相互对齐,但我不想添加额外的 html 元素,我需要图标左右对齐。
I was hoping I could give the span elements a 100% width but because of the default row direction that's not working.我希望我可以给 span 元素一个 100% 的宽度,但是因为默认的行方向不起作用。
https://codepen.io/alucardu/pen/PozBgoR https://codepen.io/alucardu/pen/PozBgoR
You can just add a div around your first block of elements:您可以在第一个元素块周围添加一个 div:
<div class="container">
<div>
<div class="icon1">+</div>
<span>Label</span>
<span>Context</span>
<div>
<div class="icon2">X</div>
</div>
this will stack your two elements without using Flex-direction: column.这将在不使用 Flex-direction: column 的情况下堆叠您的两个元素。
This works because Div's come default with Display: Block
which gives you stacked elements.这是有效的,因为 Div 默认带有Display: Block
,它为您提供堆叠元素。 Flex by default will position elements Left -> Right, which is not what you want.默认情况下,Flex 会将元素定位为 Left -> Right,这不是您想要的。
Flex in the above case on your container isn't doing much, mainly just enforcing a width.在上述情况下,您的容器上的 Flex 没有做太多事情,主要只是强制执行宽度。
Ideally, you would want to add a flex-direction:理想情况下,您需要添加一个 flex-direction:
Alternative solution:替代解决方案:
Keep your HTML the same, and use this CSS:保持你的 HTML 不变,并使用这个 CSS:
.container {
display: flex;
flex-direction: column;
width: 500px;
}
.icon1, .icon2 {
background: red;
border-radius: 50%;
padding: 8px;
color: #fff;
width: 20px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.