首页 > 解决方案 > 相对于高度的边距

问题描述

我的问题

通常在边距属性中使用百分比时,浏览器使用最近定位的祖先的宽度作为参考长度。但是我想设置我的元素相对于其父元素的边距height。这有可能吗?还是我坚持使用 JavaScript 解决方案?

一个例子

具体来说,我想要以下内容:

.child {
  height: 1em;
  width: 1em;
  background: red;
  display: inline-block;
  margin: calc((100% - 1em) / 2);
  /* margin: calc((5em - 1em) / 2); In absolute units */
  /* margin-sizing: height; If only there was some magical property like this... */
}
.container {
  background: green;
  height: 5em;
  width: 15em;
  position: relative;
}
<div class="container">
  <div class="child"></div>
  Something
</div>

看起来像这样:

期待

我知道我可以在上面的示例中使用绝对单位。但是,在更复杂或更动态的示例中,我可能并不总是知道父级的确切高度。我想为此避免使用 JavaScript。

编辑

我应该澄清一些事情。我的最终目标是上例中的红色 div 垂直居中,但与左上/下的距离相同。显然,我不一定要专门使用边距属性。但是您的解决方案的结果应该是相同的。

标签: htmlcss

解决方案


如果您可以使用margin,否则padding您会被卡住,因为这些属性的顶部和底部在用作百分比时相对于父级的宽度(正如您已经提到的那样)。

我看到的唯一解决方案是保留父元素position: relative并将top&bottom用于子元素(在 中position: absolute)以百分比形式使用。

.child {
  height: 1em;
  width: 1em;
  background: red;
  display: inline-block;
  --calc: calc((100% - 1em) / 2);
  top: var(--calc);
  left: var(--calc);
  right: var(--calc);
  bottom: var(--calc);
  position: absolute;
  /* margin: calc((5em - 1em) / 2); In absolute units */
  /* margin-sizing: height; If only there was some magical property like this... */
}
.container {
  background: green;
  height: 5em;
  width: 15em;
  position: relative;
}
<div class="container">
  <div class="child"></div>
  Something
</div>


推荐阅读