繁体   English   中英

在不使用工作台单元的情况下垂直居中并且高度未知

[英]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元素.headerText0 auto 10px的边距; margin-top0margin-bottom10px 假定元素的宽度为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM