Center content of a div vertically

2019-08-03 06:49发布

问题:

This is what Ihave so far:

http://jsfiddle.net/yisera/2aVpD/

There's a div I need to center vertically inside the .jumbotron-special container.

I tried using display: table; on he parent element and then use display:table-cell on the child element (the one with the H1 and H2) but so far no luck and I've ran out of ideas. I do not want to use absolute positioning since This needs to be responsive, and as the resolution goes smaller, the layout goes astray.

Any ideas how can I center it to the jumbotron parent div?

回答1:

You can use the following code the contents of the div .jumbotron-special

add the following properties to the class

display:flex;
 justify-content:center;
 align-items:center;

Working Code:JSFIDDLE

More on Flex Box

Read More on Flex here



回答2:

Try this:

#yourdiv {position:absolute; top:50%; height:800px; margin-top:-400px; }

Where margin-top is negative half of height.

Or, another effective method with 2 divs:

<div id="controller-div">
<div id="your-div">
Content here
</div>
</div>

Where, again with margin-bottom negative half of height:

 #controller-div    {float:left; height:50%; margin-bottom:-120px;}
 #your-div  {clear:both; height:240px; position:relative;}


回答3:

This here also works fine (you just missed to add height:100%)

.container-text{
    color: #fff;
    text-shadow: #333 3px 3px;
    display: table;
    width: 100%;
    height: 100%;
}
.inner-container {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}


回答4:

Here's another option that has a bit more support than flexbox.

Updated Fiddle here.

body{
    width: 100%;
    height: 100%;
}
.full-jumbotron{
    font-size: 10em !important;
    margin-top: -70px;
    height: 100vh;
    background: #333;
    min-height: 100%; 
    max-height: 100%;  
}
.container-text{
    color: #fff;
    text-shadow: #333 3px 3px;
    height: 100%;
    display: table;
    width:100%;
}
.inner-container {
    display: table-cell;
    vertical-align: middle;
    width:100%;
}