无论浏览器的大小如何,都有文本中心并在页面上对齐

时间:2017-12-22 01:59:30

标签: html css centering

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

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

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

然而,这并没有奏效。我该怎么做?

3 个答案:

答案 0 :(得分:1)

试试这个:

Button

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

答案 1 :(得分:0)

您可以采用多种方式,两种常见的方式是定位 Flexbox

位:

&#13;
&#13;
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 */
}
&#13;
<h1>This is center aligned text</h1>
&#13;
&#13;
&#13;

Flexbox的:

&#13;
&#13;
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 */
}
&#13;
<h1>This is center aligned text</h1>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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