子元素div#card-front超出父元素div.card-inner范围的问题求助
子元素div#card-front超出父元素div.card-inner范围的问题求助
你好呀~刚看了你的问题和代码,其实这个问题是新手学CSS时特别容易踩的盒模型坑😉
你发现#card-front比父元素.card-inner的右下侧超出、左上角却对齐,核心原因是CSS默认的盒模型是content-box:
- 你给
#card-front设置了width:100%和height:100%,这个百分比是严格基于父元素的内容区域尺寸计算的 - 同时你还加了
border:2px solid blue,这个边框是额外叠加在width/height外面的,所以#card-front的实际宽度是「父元素宽度 + 左右各2px边框」,高度是「父元素高度 + 上下各2px边框」,自然就超出父元素范围了
解决方案(推荐第一种)
方案1:使用box-sizing: border-box(最优雅省心)
给#card-front加上box-sizing: border-box;,这样CSS就会把border和padding都包含在你设置的width/height数值里,100%的尺寸就刚好贴合父元素,不会再超出了。
修改后的main.css代码:
#everything { margin-left: auto; margin-right: auto; width: 700px; } #card { background-color: transparent; height: 350px; width: 700px; padding-bottom: 10px; } .relative_element { position: relative; display: flex; justify-content: center; } .card-inner { width: 100%; height: 100%; position: relative; background-color: yellow; text-align: center; } #card-front { display: flex; align-items: center; position: absolute; width: 100%; height: 100%; border-radius: 25px; border: 2px solid blue; justify-content: center; background-color: white; color: black; font-size: 30px; box-sizing: border-box; /* 新增这一行即可解决问题 */ }
方案2:手动计算尺寸(不推荐,灵活性差)
把#card-front的宽高改成calc(100% - 4px),手动减去左右/上下边框的总宽度,但之后如果调整边框宽度,还要同步修改这个数值,远不如box-sizing省心。
另外给你个实用小技巧:可以给全局所有元素统一设置box-sizing: border-box,这样整个项目里的元素都不会再踩这个盒模型的坑了,代码加在CSS最开头就行:
* { box-sizing: border-box; }
最后提个小建议:以后遇到元素尺寸异常的问题,可以试试浏览器的开发者工具(按F12打开),它能直观展示元素的盒模型尺寸,帮你快速定位问题哦~
内容来源于stack exchange
相关产品推荐
相关产品推荐

