左侧容器图片无法占满高度的CSS问题求助
解决图片无法占满左侧div高度的问题
问题根源
.container设置了align-items: center,会让子元素在垂直方向居中,而非拉伸填满容器高度.left-side img仅定义了宽度,未设置高度,object-fit: cover缺少高度支撑无法生效.container的height: 33%依赖父元素高度,但.main-body和body未设置明确高度,导致百分比高度不生效
修复方案
修改以下CSS代码即可解决问题:
1. 调整容器对齐与高度设置
.container { background-color: var(--White); width: 33%; /* 改用视口高度或固定值,避免依赖未定义高度的父元素 */ height: 80vh; display: flex; /* 移除align-items: center,让子元素垂直拉伸填满容器 */ /* align-items: center; */ justify-content: center; overflow: hidden; margin: 4rem auto; }
2. 让图片填满左侧容器
.left-side img { width: 100%; /* 设置高度100%,配合object-fit实现比例填充 */ height: 100%; object-fit: cover; }
额外优化(可选)
如果想保留百分比高度,给父元素补充高度定义:
body { font-size: 14px; background-color: var(--Cream); color: black; height: 100vh; } .main-body { height: 100%; }
完整修改后的CSS代码
@import url(https://fonts.google.com/specimen/Fraunces); @import url(https://fonts.google.com/specimen/Montserrat); :root { --Dark-cyan: hsl(158, 36%, 37%); --Cream: hsl(30, 38%, 92%); --Very-dark-blue: hsl(212, 21%, 14%); --Dark-grayish-blue: hsl(228, 12%, 48%); --White: hsl(0, 0%, 100%) } * { margin: 0; padding: 0; box-sizing: border-box; } body { font-size: 14px; background-color: var(--Cream); color: black; height: 100vh; } .main-body { height: 100%; } .container { background-color: var(--White); width: 33%; height: 80%; display: flex; justify-content: center; overflow: hidden; margin: 4rem auto; } .left-side { width: 50%; height: 100%; overflow: hidden; } .left-side img { width: 100%; height: 100%; object-fit: cover; } .right-side { width: 50%; height: 100%; padding: 2rem; display: flex; flex-direction: column; justify-content: space-between; } h5 { font-family: "Montserrat", sans-serif; font-weight: 500; letter-spacing: 0.4rem; color: var(--Dark-grayish-blue); margin: 0 0 1em 0; } h1 { font-family: "Fraunces", serif; font-weight: 700; letter-spacing: 0.07rem; } .content { font-family: "Montserrat", sans-serif; font-weight: 500; color: var(--Dark-grayish-blue); line-height: 1.5; } .prices { font-family: "Fraunces", serif; display: inline-block; margin: 0 0.5em; } .old-price { text-decoration: line-through; vertical-align: middle; } .new-price { font-weight: 700; color: var(--Dark-cyan); font-size: 2rem; } .btn { padding: 0.8em 1.8em; background-color: var(--Dark-cyan); color: var(--White); width: 100%; border: none; border-radius: 8px; cursor: pointer; font-family: "Montserrat", sans-serif; font-weight: 700; } .btn:hover { background-color: hsl(158, 36%, 25%); }
补充说明
- 移除
align-items: center后,flex子元素会自动垂直拉伸,填满容器高度 - 图片设置
height: 100%后,object-fit: cover才能生效,保证图片按比例填充且不变形 - 优化了右侧内容布局,让元素分布更合理,同时调整了按钮、价格的样式细节
内容的提问来源于stack exchange,提问作者Kannav02
相关产品推荐
相关产品推荐

