我在HTML中使用标签<h1>
,我试图将文本放在网页的中间,无论你改变了多少网页的大小。基本上,文本也响应网页的大小。这就是我的意思:
在我的css页面中,我尝试执行以下操作:
h1 {
text-align: center;
display: table-cell;
vertical-align: middle;
}
但是,这不起作用。我该怎么做?
您可以采用多种方式,两种常见的方式是定位和Flexbox:
定位:
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>This is center aligned text</h1>
试试这个:
body{
position:relative;
}
h1{
position:absolute;
width: /*your desired width*/
top:0;
bottom:0;
left:0;
right:0;
margin:auto auto;
text-align:center;
}
注意:当您使用绝对子类时,父类始终是相对的。
作为一个表格单元格,正如你所尝试的那样工作但它是包装器而不是h1元素要成为“表格单元格”,所以h1可以垂直居中到中间。要使该单元覆盖整个屏幕,您可以使用100vh高度和100wv宽度...或使用4个角固定位置以强制它覆盖整个屏幕(顶部; 0,左:0,右:0,底部:0 )。