如何让容器内div元素宽度匹配文本最大宽度?
让文本元素宽度适配自身内容的解决方案
问题描述
有一个固定宽度的容器,内部的.link元素当前宽度为父容器的100%,需要让它的宽度等于文本的最大宽度(即仅包裹文本内容,不占满父容器)。
解决方案
可以通过以下两种简单的CSS修改实现需求:
方法1:使用display: inline-block
给.link元素添加display: inline-block,块级元素转为行内块后会自动收缩宽度以适配内容:
.link { font-size: 28px; font-weight: 400; line-height: 1.3; cursor: pointer; border-bottom: 2px dashed; display: inline-block; /* 添加这一行 */ }
方法2:使用width: fit-content
利用CSS的fit-content属性,直接让元素宽度适配内容:
.link { font-size: 28px; font-weight: 400; line-height: 1.3; cursor: pointer; border-bottom: 2px dashed; width: fit-content; /* 添加这一行 */ }
完整修改后的代码
HTML(无需修改)
<div id="app"> <div class="container"> <div class="links-container"> <div class="link">With built in wardrobes</div> </div> </div> </div>
CSS(以width: fit-content为例)
#app { width: 100%; height: 100%; margin: 0px auto; display: flex; justify-content: center; background-color: gray; } .container { width: 200px; height: 500px; background-color: rgba(180, 0, 200, 0.3); display: flex; justify-content: center; } .links-container { display: flex; flex-direction: column; align-items: start; row-gap: 20px; max-width: 100%; } .link { font-size: 28px; font-weight: 400; line-height: 1.3; cursor: pointer; border-bottom: 2px dashed; width: fit-content; }
注:
fit-content是现代浏览器都支持的属性,兼容性良好;如果需要兼容旧版浏览器,inline-block是更稳妥的选择。
内容的提问来源于stack exchange,提问作者Vladislav Yurevich
相关产品推荐
相关产品推荐

