CSS设置的div高度未生效问题求助(拒绝使用min-height)
问题:设置的div高度未生效,容器自动采用类似min-height的高度
我计划用两类
模拟杯子,分别是一个大杯和多个小杯,但设置的
高度并未生效。由于需要缩小小杯的尺寸,我不想给
.cup类设置min-height属性。我的代码:
CSS代码
@import url('https://fonts.googleapis.com/css?family=Montserrat:400,600&display=swap'); :root { --border-color: #144fc6; } * { box-sizing: border-box; } body { background-color: #3494e4; color: #fff; font-family: 'Montserrat', sans-serif; display: flex; flex-direction: column; align-items: center; height: 100vh; margin-bottom: 40px; } h1 { margin: 10px 0 0; } h3 { font-weight: 400px; margin: 10px 0; } .cup { background-color: #fff; border: 4px solid var(--border-color); color: var(--border-color); border-radius: 0 0 40px 40px; height: 330px; width: 150px; margin: 30px 0; display: flex; flex-direction: column; overflow: hidden; } .cup.cup-small { width: 50px; height: 95px; }
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PK0gIY59xJ8Co8+NEgFZ+L0AZKjy+KY8iq0G4B3CyeY&wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> <title>Drink Water</title> </head> <body> <h1>Drink Water</h1> <h3>Goal: 2 Liters</h3> <div class="cup"> <div class="remained" id="remained"> <span id="'Liters">1.5L</span> <small>Remained</small> </div> <div class="percentage" id="percentage"> 20% </div> </div> <p class="text"> Select how many glasses of water tat you have drank. </p> <div class="cup cup-small full"> 250 ml </div> <div class="cup cup-small full"> 250 ml </div> <div class="cup cup-small"> 250 ml </div> <div class="cup cup-small"> 250 ml </div> <div class="cup cup-small"> 250 ml </div> <div class="cup cup-small"> 250 ml </div> <div class="cup cup-small"> 250 ml </div> <div class="cup cup-small"> 250 ml </div> <script src="script.js"></script> </body> </html>
问题原因
你给.cup设置了display: flex和flex-direction: column,而flex容器默认的align-items属性值是stretch。这个值会让flex子元素自动拉伸,填满容器的交叉轴高度(也就是垂直方向,因为flex-direction是column)。对于小杯来说,里面的文本内容会触发这个拉伸行为,导致容器高度被撑开,看起来像是有min-height的效果,覆盖了你设置的height值。
解决方案
给.cup添加align-items: center(或者其他非stretch的值,比如flex-start),这样子元素就不会强制拉伸撑满容器高度,你指定的height就能正常生效。如果需要让小杯里的文本居中显示,还可以加上justify-content: center。
修改后的.cup CSS代码:
.cup { background-color: #fff; border: 4px solid var(--border-color); color: var(--border-color); border-radius: 0 0 40px 40px; height: 330px; width: 150px; margin: 30px 0; display: flex; flex-direction: column; overflow: hidden; align-items: center; /* 新增:取消子元素拉伸 */ justify-content: center; /* 可选:让文本垂直居中 */ }
另外,注意你的HTML里<span id="'Liters">多了一个多余的单引号,建议改成<span id="Liters">,避免后续JavaScript获取元素时出错。
内容的提问来源于stack exchange,提问作者Coding Newbie
相关产品推荐
相关产品推荐

