如何使用原生CSS或Tailwind让:after伪元素边框延伸至容器末尾
实现方案
原生CSS方案
核心思路是让标题容器自身占满父级flex容器的全部宽度,再通过flex布局让伪元素自动填充剩余横向空间:
修改后CSS代码
/* 父容器保留原有flex属性即可,无需修改 */ .subheading { display: flex; align-items: center; gap: 20px; /* 控制文字和横线的间距,替代原伪元素的margin-left */ flex: 1; /* 让标题元素占满section容器的全部可用宽度 */ } .subheading:after { background-color: rgb(194, 188, 178); content: ""; height: 0.25rem; flex-grow: 1; /* 核心属性:自动占满当前行剩余横向空间 */ }
HTML代码无修改
<section class="flex"> <h1 class="subheading">Coronovirus</h1> </section>
Tailwind方案
直接通过Tailwind内置类实现,无需额外编写自定义CSS:
<section class="flex"> <h1 class="flex items-center gap-5 flex-1 after:content-[''] after:h-1 after:bg-[#c2bcb2] after:flex-grow"> Coronovirus </h1> </section>
注:如果需要限制整个模块的最大宽度,直接给外层section添加max-width相关属性即可,横线会自动适配容器实际宽度。
内容的提问来源于stack exchange,提问作者IOIOIOIOIOIOI
相关产品推荐
相关产品推荐

