首页 > 解决方案 > CSS填充父级

问题描述

我希望蓝色 div 不会溢出红色 div,但总是填充父级。我检查了 stackoverflow,他们建议使用 height:100% 但由于孩子有填充,它会溢出。如何在不改变父类风格的情况下做到这一点?

.parent {
  background: red;
  height: 150px;
  width:300px;
}
.child{
  height: 100%;
  padding:20px;
  width:100px;
 background: blue; 
}
<div class='parent'>
  <div class='child'>
  
  </div>
  </div>

标签: htmlcss

解决方案


您可以使用box-sizing: border-box;,也可以计算孩子的身高,例如height: calc(100% - 40px */ Your padding */

解决方案1

* {
  box-sizing: border-box;
}

.parent {
  background: red;
  height: 150px;
  width: 300px;
}

.child{
  height: 100%;
  padding: 20px;
  width: 100px;
  background: blue;
}

解决方案2

.parent {
  background: red;
  height: 150px;
  width: 300px;
}

.child{
  height: calc(100% - 40px);
  padding: 20px;
  width: 100px;
  background: blue;
}

推荐阅读