首页 > 解决方案 > CSS相对响应高度

问题描述

#parent {
  position: fixed;
  width: 600px;
  height: 300px;
  background: red;
}

#child {
  position: relative;
  width: 200px;
  margin-bottom: 10px;
  margin-top: 10px;
  height: auto;
  background: blue;
}
<div id="parent">
  <div id="child"></div>
</div>

我想让孩子拥有父母的身高减去边距。为什么高度是0px?

JSFiddle

标签: htmlcss

解决方案


height: auto只是“自动与它所包含的内容一样大”。如果你想明确地使它的高度减去边距,你可以设置height: calc(100% - 20px);

#parent {
  position: fixed;
  width: 600px;
  height: 300px;
  background: red;
}

#child {
  position: relative;
  width: 200px;
  margin-bottom: 10px;
  margin-top: 10px;
  height: calc(100% - 20px);
  background: blue;
}
<div id="parent">
  <div id="child"></div>
</div>


推荐阅读