【问题标题】:The 'top' CSS attribute does not apply with 100vh'top' CSS 属性不适用于 100vh
【发布时间】:2016-06-28 06:30:56
【问题描述】:

我正在尝试构建一个仅使用 css 的简单单页网站,作为熟悉 css 的练习。

我将三个背景图像堆叠在一起。每个图像设置为 100vh 的高度。这使每个图像看起来都很好,但我尝试使用“顶部”属性将文本放置在页面中间,文本没有移动。

谁能告诉我为什么'top'在这种情况下不起作用?以及解决方法?

This is my CSS: 

#page1 {
    background-size: cover;
    background-image: url('Page1_f09078_f06078_1000_vertical.png');
    height: 100vh;  
    display: block;
}

#welcome {
    text-align: center;
    top: 50%;                <-- This attribute won't work
}

#page2 {
    background-size: cover;
    display: block;
    background-image: url('Page2_f06078_ffa860_1000_vertical.png');
    height: 100vh;  
}

#page3 {
    background-size: cover;
    display: block;
    background-image: url('Page3_ffa860_f09078_1000_vertical.png');
    height: 100vh;
}

这是我的html:

<html lang="en">
  <head>
  <link href="SinglePage.css" rel="stylesheet">
  </head>
    <body>

      <div id="page1">

        <h2 id="welcome">Welcome!</h2>


      </div> <!-- End of page1 -->

      <div id="page2">
      </div>

      <div id="page3">
      </div>



   </body>
</html>

【问题讨论】:

  • topleftrightbottom 属性仅适用于定位元素。

标签: html css viewport-units


【解决方案1】:

topleftrightbottom css 属性仅在与 relativeabsolutefixed 位置一起使用时才有效。

使用以下css:

#page1 {
  position: relative;
}

#welcome {
  transform: translateY(-50%);
  text-align: center;
  position: absolute;
  top: 50%;
  right: 0;
  left: 0;
}

【讨论】:

    【解决方案2】:

    添加位置:相对;

    #welcome {
        position: relative;
        text-align: center;
        top: 50%;
    }
    

    【讨论】:

      【解决方案3】:

      top、right、bottom 和 left 属性指定定位元素的位置。 通过此链接:https://developer.mozilla.org/en/docs/Web/CSS/position

      【讨论】:

        猜你喜欢
        • 2013-08-28
        • 1970-01-01
        • 2017-10-31
        • 2021-10-23
        • 2021-08-07
        • 2020-10-06
        • 2017-10-31
        • 2016-07-16
        • 1970-01-01
        相关资源
        最近更新 更多