为何.box元素渲染宽度为139px而非指定的120px?
布局异常问题
预期.box元素宽度为120px,但实际渲染宽度为139px,相关代码如下:
CSS代码
*{ box-sizing: border-box; margin: 0; padding: 0; } .box{ position: absolute; background-color: red; min-width: 24px; } .input{ min-width: 0; width: 100%; border: none; padding: 0; background: transparent; outline: none; border-bottom: 1px solid blue; } .text{ min-width: 120px; }
HTML代码
<div class="box"> <input class="input" /> <div class="text">Text</div> </div>
异常原因
.box是绝对定位元素,未设置width属性时,其宽度由内部子元素的最小宽度总和决定.text元素设置了min-width:120px,但input作为表单元素,浏览器会默认给它分配一个最小宽度(不同浏览器数值略有差异,此处约为19px)- 两者最小宽度相加(120px + 19px),最终导致
.box渲染宽度为139px,超出预期值
解决思路示例
如果要让.box固定为120px宽度,可以给.box显式设置width,同时调整子元素的宽度规则适配父容器:
.box{ position: absolute; background-color: red; min-width: 24px; width: 120px; /* 新增固定宽度 */ } .text{ min-width: 120px; width: 100%; /* 让文本容器适配父容器宽度 */ }
内容的提问来源于stack exchange,提问作者ryan
相关产品推荐
相关产品推荐

