我有一个标题文本和一个图标。
如果标题可以容纳一行,我需要将图标向左对齐。
如果标题超过一行,那么我必须将图标对齐到顶部。
我找到了一个使用Javascript的解决方案,通过附加一个基于高度和行高的动态类。
这听起来像是可以用以下方法解决的问题。屈曲.
你正在寻找的财产 flex-wrap
. 在你的情况下,flex会让你的项目保持在行内,除非一个项目太长,在这种情况下,它会把它包到下一行。
CSS代码应该是这样的。
.item{
display:flex;
justify-content:center;
flex-wrap:wrap;
}
.icon{
flex-shrink:0;
}
HTML应该是这样的
<div class="item">
<div class="icon"></div>
<div class="text">aaaaaaaaaa</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="text">
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</div>
</div>
你的 item
将是你应该分配给flex的那个。
将图标作为一个伪元素,就像我通过css添加的那样。
div{
margin: 1em 0;
border: 1px solid black;
padding: 2em;
position: relative;
}
div::before {
position: absolute;
left: 0;
content:"icon";
}
<div>My Content</div>
<div>My Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log Contentttttttttttttttttttttttttttttttttttt</div>
首先你在根元素中添加图标和文本元素。
<div class="root">
<div class="icon">Icon</div>
<div class="text">Text</div>
</div>
这个根元素的样式。
.root{
display: flex;
flex-wrap: wrap;
}