div搭配img元素时overflow:hidden属性不生效是什么原因?
问题原因
- 属性拼写错误:你写的
over-flow:hidden是错误语法,正确的溢出隐藏属性是overflow: hidden,名称中间没有连字符,这是导致属性不生效的最直接原因。 - 百分比高度失效:
height: 30%是相对父元素高度计算的属性,如果.container的上层父元素(如<body>、<html>)没有设置明确的高度值,这个30%设置不会生效,容器高度会默认由内部内容撑开,自然无法触发溢出裁剪效果。
修正方案
首先修正CSS属性拼写,其次给百分比高度依赖的上层元素设置明确高度,也可以直接改用视口单位vh替代百分比,避免依赖父元素高度:
/* 方案1:保留百分比高度,给上层元素设置基础高度 */ html, body { height: 100%; margin: 0; } .container{ position: relative; width: 20%; height: 30%; overflow: hidden; background-color: yellow; } .container img{ position: absolute; width: 100%; /* 可选优化:让图片等比例铺满容器,避免拉伸变形 */ height: 100%; object-fit: cover; } .container .txt{ position: absolute; top: 0; height: 100%; width: 100%; color: #fff; background-color: rgba(0, 0, 0, .4); }
/* 方案2:改用vh单位,无需依赖父元素高度 */ .container{ position: relative; width: 20%; height: 30vh; /* 占视口高度的30% */ overflow: hidden; background-color: yellow; }
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

