我该如何让元素跟随文本?
我希望“line”和“square”这两个元素始终紧跟文本,line能占满剩余的可用空间,且在换行时line和 square不会被分离。
.component {
display: flex;
flex-direction: row;
gap: 10px;
}
.line-and-square {
display: flex;
flex: 1;
align-items: center;
gap: 10px;
}
.line {
height: 3px;
background-color: red;
flex: 1;
}
.square {
width: 20px;
height: 20px;
background-color: red;
}
<div class="component">
<h1 class="title">How can you ensure that the line follows the text in all circumstances?</h1>
<div class="line-and-square">
<div class="line"></div>
<div class="square"></div>
</div>
</div>
当前结果如下:

就渲染目标而言,我想达到的是:

或者:

我就做不到。请问你有什么解决办法?
解决方案
下面给出第一种布局的一个思路,使用最简的HTML代码:
h1 {
overflow: hidden;
position: relative;
padding-right: 30px; /* equal to square size + gap */
}
/* the line */
h1:after {
content:"";
display: inline-block;
vertical-align: bottom;
height: 5px; /* line height */
border-image: conic-gradient(red 0 0) 0 1/0 100vw 0 0/0 100vw 0 0;
translate: 10px /* gap*/ calc(50% - .5lh)
}
/* the square */
h1:before {
content: "";
position: absolute;
right: 0;
bottom: 0;
width: 20px; /* square size */
aspect-ratio: 1;
border: 5px /* gap */ solid #fff;
background: red content-box;
translate: 0 calc(50% - .5lh);
z-index: 1;
}
<h1 class="title">How can you ensure that the line follows the text in all circumstances?</h1>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。