div元素存在但页面不显示 absolute定位图片宽高为0如何解决
目标效果

问题根因
两个异常都是CSS设置疏漏导致:
- 红色div不显示:仅给
.small-red-box设置了文字颜色color: white,未设置背景色,空div默认透明,肉眼不可见。 - 图片设为绝对定位后宽高归零:
- 选择器
.wrap_Container div会命中容器内所有层级的div,包括.big-box,覆盖了.big-box原本的布局属性; - 绝对定位元素脱离普通文档流,
.big-box内两个子元素全部设为绝对定位后,没有普通流元素撑起容器尺寸,父容器宽高坍缩为0,此时图片设置的width: 20%(百分比值相对最近的已定位父元素计算)失去计算基准,宽高直接变为0; - 未设置两个叠放元素的层级和偏移,就算红块加了背景也无法实现错位露出的效果。
- 选择器
修复步骤
- 给
.small-red-box添加红色背景,设置偏移量实现和图片错位叠放的效果; - 缩小选择器命中范围,将
.wrap_Container div改为.wrap_Container > div,只选中容器直接子项,避免误伤内部的.big-box元素; - 给
.big-box设置和设计匹配的固定宽高,或者保留一个普通流内的子元素撑起容器尺寸,让绝对定位子元素的百分比宽高有计算基准; - 调整红块和图片的z-index,红块层级低于图片,实现红块在图片后方错位露出的效果。
修改后可用代码
/* Why choose Section */ #Why_choose{ height: 100%; background: #141414; padding: 2rem 0; } .wrap_Container{ display: flex; align-items: flex-start; justify-content: center; text-align: center; margin-top: 3.5rem; margin-bottom: 2rem; gap: 2rem; } /* 仅选中wrap_Container的直接子div,避免覆盖内部big-box样式 */ .wrap_Container > div{ display: flex; flex-direction: column; justify-content: center; align-items: center; } #Why_choose h1{ color: white; font-size: 3.5rem; text-align: center; margin: 0; } #Why_choose h2{ color: white; font-family: 'Roboto Condensed', sans-serif; font-weight: 700; font-size: 1.5rem; width: 80%; margin-bottom: 0; margin-top: 1.5rem; } #Why_choose p{ color: white; font-family: 'Roboto Condensed', sans-serif; font-weight: 300; font-size: 1rem; line-height: 1.5rem; width: 80%; } .Why_heading{ position: relative; height: 25vh; display: flex; align-items: center; justify-content: center; } .Why_heading h1{ position: absolute; top: 20%; } .big-box{ position: relative; /* 给容器设置固定宽高,避免子元素全部绝对定位后容器坍缩 */ width: 240px; height: 300px; display: flex; align-items: center; justify-content: center; } #Why_choose img{ width: 200px; position: relative; z-index: 10; } #Why_choose .small-red-box{ /* 新增红色背景 */ background: #e63946; width: 200px; height: 260px; z-index: 9; position: absolute; /* 错位偏移量,可根据设计稿调整 */ top: 20px; left: 20px; }
说明:如果需要保留图片的绝对定位设置,只需给图片明确设置固定宽高+偏移量即可,不需要修改定位属性。红块、图片的尺寸和偏移数值可以根据实际素材尺寸调整到和参考图一致。
内容的提问来源于stack exchange,提问作者Sahil Singh
相关产品推荐
相关产品推荐

