【问题标题】:Having text center and aligned on the page no matter what the size of the browser is无论浏览器大小如何,文本居中并在页面上对齐
【发布时间】:2017-12-22 19:58:35
【问题描述】:

我在 HTML 中使用标签 <h1>,并且我试图将文本放在网页的中间,无论您如何更改网页的大小。基本上,文本也响应网页的大小。这就是我的意思:

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

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

但是,这不起作用。我该怎么做?

【问题讨论】:

标签: html css centering


【解决方案1】:

您可以通过多种方式做到这一点,两种常见的方式是 positioningFlexbox

定位:

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>

弹性盒:

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>This is center aligned text</h1>

【讨论】:

    【解决方案2】:

    试试这个:

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

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

    【讨论】:

    • 子标题也要居中?然后将标题和副标题包装到 div 中,然后将绝对位置应用于该 div
    • 在你的代码中试试这个。代码笔导致身高问题,您只需在您的代码中尝试
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 2022-01-15
      相关资源
      最近更新 更多