How to keep text inside a div, always in the middle?

Flexbox has really changed the game with aligning elements in a fluid manner. Define your container element to be display: flex and then to align your inner children you would use justify-content: center; align-items: center;

.container {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}
.parent {
    height: 500px;
    width: 500px;
    position: relative;
}


<div class="parent">
    <div class="container">
        <p>Hello</p>
        <p>World</p>
    </div>
</div>

You'll notice that "Hello" and "World" will both be vertically and horizontally centered within the .container element.


If you don't care about IE7 support, you can do it like that:

HTML:

<div id=wrap>
  <div id=inside>
    Content, content, content.
  </div> 
</div>

CSS:

#wrap {
    /* Your styling. */
    position: absolute;
    z-index: 999999;
    right: 0;
    height: 60%;
    text-align: center;

    /* Solution part I. */
    display: table;
}

/* Solution part II. */
#inside {
    width: 100%;
    height: 100%;
    display: table-cell;
    vertical-align: middle;
}

The code: http://tinkerbin.com/ETMVplub

If you're OK with JavaScript you can try this jQuery plugin: http://centratissimo.musings.it/ but since it also doesn't seems to support IE7 the CSS solution is probably better.


Replace height: 60%; with padding: 30% 0;.

Tags:

Html

Css