[英]How to vertically center the text without using display: table-cell?
[英]Vertically center without using table-cell and with an unknown height
我正在尝试居中放置一个高度未知的文本块,并且表格单元格也将无法工作(宽度必须是父母的100%)。 我要居中的部分是headerText p类。 我在下面包含了html / css。 任何帮助将非常感谢!
HTML
<div class="headerContent">
<a href="#" class="scrollup">Scroll</a>
<a href="#windSection" id="scrolldown">Scroll</a>
<h1 class="title">Title</h1>
<p class="headerText">
TEST GOES HERE. THIS IS THE TEXT I AM TRYING TO CENTER. IT HAS NO SET HEIGHT.>
</p>
<div class="green select">
<a class="button" href="links/calculator.html">Discover</a>
</div>
<img class="people" src="images/people.png" />
<p class= "noElechouse"></p>
</div>
CSS:
.headerContent {
position:relative;
width:55%;
margin:auto;
height:100%;
text-align:center;
}
.title {
font-family: 'Oxygen', sans-serif;
font-weight:700;
color:white;
font-size:90px;
padding-bottom:15px;
}
.headerText {
font-family: 'Oxygen', sans-serif;
font-weight:400;
font-size:18px;
line-height:27px;
width:90%;
margin:auto;
}
就您而言,您不需要为此使用JavaScript。
首先从.title
元素中删除padding-bottom:15px
,并将margin
值设置为0
。 然后给.headerText
元素.headerText
出0 auto 10px
的边距; 将margin-top
为0
, margin-bottom
为10px
。 假定元素的宽度为90%
,则将auto
用于水平居中。 垂直对齐不再是问题,因为两个垂直相邻的元素的分隔边距均为10px
。
.title {
font-family:'Oxygen', sans-serif;
font-weight:700;
font-size:90px;
padding:0;
margin:0;
}
.headerText {
font-family:'Oxygen', sans-serif;
font-weight:400;
font-size:18px;
width:90%;
margin:0 auto 10px;
}
或者,您也可以使用以下内容:
.headerText {
font-family:'Oxygen', sans-serif;
font-weight:400;
font-size:18px;
width:100%;
margin:0 auto 10px;
display:table-cell;
vertical-align:middle;
text-align:center;
}
在不知道高度的情况下,您将不得不使用百分比来估算其大小,即
.headerText { width:90%; height:50%; margin:25% 5%; }
或使用javascript将其垂直居中
#headerText { width:90%; top:50%; margin:0 5%; } //CSS
var eh = document.getElementByID('headerText'); //change from class to ID
eh.margin.top = -(eh/2);
或所有jQuery
ht = $('.headerText');
elH = ht.height();
wH = $(window).height();
marginTop = (wH/2)-(elH/2);
ht.css('margin-top',-marginTop);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.