代码之家  ›  专栏  ›  技术社区  ›  fairlyMinty

无论浏览器大小如何,都在页面上保持文本中心和对齐

  •  0
  • fairlyMinty  · 技术社区  · 8 年前

    我正在使用标签 <h1> 在HTML中,我试图将文本放在网页的中间,无论你如何改变网页的大小。基本上,文本也会对网页的大小做出响应。我的意思是:

    在我的css页面中,我尝试执行以下操作:

    h1 {
     text-align: center;
     display: table-cell;
     vertical-align: middle;
    }
    

    然而,这并没有起作用。我该怎么做?

    3 回复  |  直到 8 年前
        1
  •  1
  •   VXp Kadir BuÅ¡atlić    8 年前

    您可以通过多种方式来实现这一点,有两种常见的方法 定位 和 柔性箱 :

    定位:

    body {
      position: relative; /* usually the parent, in this case the body element, has position relative so that the absolute positioned child is positioned relative to it */
      height: 100vh; /* 100% of the viewport height */
      margin: 0; /* recommended */
    }
    
    h1 {
     position: absolute; /* taken out of the normal flow of the document */
     top: 50%; /* moved down by 50% of the screen height */
     transform: translateY(-50%); /* moved back up (Y axis) by half of its height to achieve the perfect center */
     width: 100%; /* needs to be defined to keep the default block behavior */
     text-align: center;
     margin: 0; /* again, for perfect center */
    }
    <h1>This is center aligned text</h1>

    Flexbox:

    body { /* or any other parent element */
      display: flex; /* flex behavior (displays children inline) */
      justify-content: center; /* horizontal centering */
      align-items: center; /* vertical centering */
      height: 100vh;
      margin: 0;
    }
    
    h1 {
      text-align: center; /* comes in handy when resizing the browser width, if the text is long/big enough */
    }
    <h1>这是居中对齐的文本(</h1>
        2
  •  1
  •   pradeep kumar    8 年前

    试试这个:

     body{
           position:relative;
        }
    
        h1{
           position:absolute;
           width: /*your desired width*/
           top:0;
           bottom:0;
           left:0;
           right:0;
           margin:auto auto;
           text-align:center;
        }
    

    注意:使用绝对子类时,父类始终是相对的。

        3
  •  0
  •   miguel-svq    8 年前

    正如您所尝试的那样,作为一个表单元是可行的,但它是包装器而不是h1元素,因此h1可以垂直居中到中间。要使该单元格覆盖整个屏幕,可以使用100vh高度和100wv宽度。。。或使用4个角固定位置,以强制其覆盖整个屏幕(顶部;0,左侧:0,右侧:0,底部:0;)。