首页 > 解决方案 > 无法在 ::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 下而不是在它的中心...

标签: htmlcsssass

解决方案


你想要完成的是让 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%;
}


推荐阅读