css - flexbox 对齐从中心偏移的项目,没有填充物
问题描述
使弹性项目居中很容易。但是我喜欢将它向上移动一点,这样上下空间之间的关系就是例如 1/2。使用填充物时也很容易。但是有没有办法在没有填充物的情况下做到这一点?HTML:
<div id="filler-top"></div>
<div id="the-item">
</div>
<div id="filler-bottom"></div>
CSS:
#the-item {
width: 80vw;
height: 30vh;
border: 2px solid lightblue;
}
body {
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
#filler-top {
width: 100%;
flex: 1;
}
#filler-bottom {
width: 100%;
flex: 2;
}
https://jsfiddle.net/Sempervivum/b2wotc8e/3/
应用 margin-top 和 margin-bottom 不起作用,因为百分比是相对于宽度的。
解决方案
您可以使用伪元素:before
,而不是向标记添加 2个元素::after
#the-item {
width: 80vw;
height: 30vh;
border: 2px solid lightblue;
}
body {
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
body:before {
content: "";
width: 100%;
flex: 1;
}
body:after {
content: "";
width: 100%;
flex: 2;
}
<div id="the-item"></div>
另一种选择是简单地使用position:relative
,top
和的混合transform
:
#the-item {
width: 80vw;
height: 30vh;
border: 2px solid lightblue;
position: relative;
top: 33.333%;
transform: translateY(-33.333%);
}
body {
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
<div id="the-item"></div>
推荐阅读
- c++ - 我的 hdc/hbitmap 的内存泄漏在哪里?
- spring - 当我在不同的 @Configuration 类中添加多个 @ComponentScan 时会发生什么
- c++ - c ++ fstream只输出一种情况
- c# - 使用 SAML 2.0 协议获取 SAML 2.0 断言 XML
- r - 检测两个序列之间的差异
- java - RecyclerView中如何处理多个RecyclerView
- google-cloud-platform - 创建 Kubernetes 集群的权限
- c# - Exchange Web 服务 - 尝试读取消息属性时出现“您必须先加载或分配此属性才能读取其值”错误消息
- sql - 具有多个标题和多个计数的 sql 查询
- python - 使用 pandas 将独立标题添加到 csv 文件