html - 无法在 ::before div 中居中段落
问题描述
div.st-header-image {
width: 100%;
background-color: #a7b885;
margin: 0px;
text-align: center;
overflow: hidden;
}
div.st-header-image p.st-description {
margin: 0px;
color: red;
font-size: 40px;
line-height: 40px;
vertical-align: middle;
}
div.st-header-image ::before {
content: " ";
padding-top: 40%;
display: inline-block;
}
<body>
<div class="st-header-image">
<p class="st-description">Header Image</p>
</div>
</body>
我正在尝试制作一个需要在具有 ::before 样式的 div 内的段落,因此当我增加或减少分辨率时它会改变大小。
我尝试使用不同的溢出,不同的显示...还尝试使用 calc((100% - 40px) / 2) 来定位顶部/底部,但它似乎也不起作用。
div.st-header-image
{
width:100%;
background-color: rgb(167, 184, 133);
margin:0px;
text-align: center;
overflow: hidden;
p.st-description
{
margin:0px;
color:red;
font-size:40px;
line-height: 40px;
vertical-align: middle;
}
::before
{
content: " ";
padding-top: 40%;
display: inline-block;
}
}
p 元素在 div 内,类 st-header-image
div 是响应式的,但段落一直显示在 div 下而不是在它的中心...
解决方案
你想要完成的是让 div 在顶部有一个响应空间,并且在它的响应过程中段落粘在中间。我修复了没有::before
伪元素的代码。
使用 div 的填充和一些定位可以实现相同的功能。
我在这里分享了 repl.it 上的代码
这是您需要的 CSS:
div.st-header-image {
width: 100%;
background-color: #a7b885;
margin: 0px;
text-align: center;
overflow: hidden;
padding-top: 40%;
position: relative;
}
p.st-description {
margin: 0px;
color: red;
font-size: 40px;
position: absolute;
top: 0;
left: 0;
right: 0;
text-align: center;
padding-top: 15%;
}
推荐阅读
- java - 在 PostgreSQL 数据库中插入带有 jOOQ 的 SQL 枚举
- rust - 如何从 Chrono::DateTime 中获取年月日组件?
- python - Docker 容器中的 Selenium 找不到 chromedriver
- php - Google Drive API - 使用 PHP Curl 可恢复上传无响应
- woocommerce - Wocomerce 自定义支付网关
- docker - 从 github 构建 grafana 的生产自定义 docker 镜像
- api - YouTube 数据 API 未实时返回
- performance - 二分查找的实际效率
- r - 子集嵌套列表以仅包含在向量中命名的元素
- c++ - 将 std::sort 与并行执行策略一起使用时,我必须考虑什么?