Flexbox子项宽度无法适配内容宽度的技术求助
Flexbox子项适配内容宽度的解决方案
问题描述
我遇到了Flexbox子项的问题:它无法适配内容宽度。使用flex-grow: 1;会让元素占据全部空间,但我不希望如此。我需要<div class="d-flex align-items-center"></div>仅占据自身内容的宽度,而非父容器的全部宽度。
原始代码
CSS
.pw-event-options { -webkit-box-flex: 0; -webkit-flex: 0 0 280px; -moz-box-flex: 0; -ms-flex: 0 0 280px; flex: 0 0 280px; max-width: 280px; } .pw-list-item-item { display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; padding-left: 10px; padding-right: 10px; } .align-items-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -moz-box-align: center !important; -ms-flex-align: center !important; align-items: center !important; } .d-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -moz-box !important; display: -ms-flexbox !important; display: flex !important; } .pw-list-item-item.pw-event-options a { border: 6px solid rgba(0, 0, 0, 0); display: inline-block; -webkit-box-flex: 0; -webkit-flex: 0 0 80px; -moz-box-flex: 0; -ms-flex: 0 0 80px; flex: 0 0 80px; margin-right: 50px; max-width: 80px; outline: none; text-decoration: none; -webkit-transition: all .3s ease-in-out 0s; -o-transition: all .3s ease-in-out 0s; -moz-transition: all .3s ease-in-out 0s; transition: all .3s ease-in-out 0s; } .pw-list-item-item.pw-event-options .pw-moderation-type { -webkit-box-align: center; -webkit-align-items: center; -moz-box-align: center; -ms-flex-align: center; align-items: center; background-color: #ececec; -webkit-border-radius: 20.5px; border-radius: 20.5px; color: #222; display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; -webkit-box-flex: 0; -webkit-flex: 0 0 130px; -moz-box-flex: 0; -ms-flex: 0 0 130px; flex: 0 0 130px; font-size: 26px; font-family: "Montserrat", sans-serif; font-weight: 500; height: 41px; -webkit-box-pack: center; -webkit-justify-content: center; -moz-box-pack: center; -ms-flex-pack: center; justify-content: center; line-height: 1.2307692308; max-width: 130px; }
HTML
<div class="pw-list-item-item pw-event-options"> <div class="d-flex align-items-center"> <a href="javascript:void(0);"> <svg width="512" height="512" viewBox="0 0 512 512"></svg> </a> <div class="pw-moderation-type">OFF</div> </div> </div>
效果示意图

解决方案
问题核心是:.d-flex类设置的display: flex会让元素成为块级flex容器,默认占据父容器全部宽度。以下三种方法都能让它仅适配内容宽度:
方案1:改为行内flex容器
给目标元素添加行内flex的样式,覆盖原有的块级flex设置:
.d-flex.align-items-center { display: inline-flex !important; }
方案2:强制宽度适配内容
直接设置宽度为内容所需的最小宽度:
.d-flex.align-items-center { width: fit-content; }
方案3:调整父flex容器的子项属性
目标div是.pw-list-item-item(父flex容器)的直接子项,设置flex: 0 0 auto让它在主轴上不拉伸、不收缩,宽度由内容决定:
.pw-event-options .d-flex.align-items-center { flex: 0 0 auto; }
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

