html - 相对于高度的边距
问题描述
我的问题
通常在边距属性中使用百分比时,浏览器使用最近定位的祖先的宽度作为参考长度。但是我想设置我的元素相对于其父元素的边距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 垂直居中,但与左上/下的距离相同。显然,我不一定要专门使用边距属性。但是您的解决方案的结果应该是相同的。
解决方案
如果您可以使用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>
推荐阅读
- mongodb - Mongodb查询仅获取特定日期的文档
- python - 使用多个 python 列表时避免使用 `i` 进行索引
- python - ValueError: 操作数不能与形状 (0,) (784,) 一起广播
- python - 根据另一列(条件)的值替换缺失值 NAN
- oauth-2.0 - JHIpster KeyCloak OAuth,登录期间代理错误
- mongodb - 带有参数的axios获取请求不起作用
- c# - 验证字符串预防不起作用?
- javascript - 如何使用 JavaScript 中的 PATCH 请求将项目添加到数据库中的数组?
- c# - 如何检测函数指针类型?
- php - 折扣购物车项目价格不包括 WooCommerce 中的类别及其子项