allegutta allegutta - 1 year ago 419
HTML Question

Center text over an image in flexbox

How can I centre align text over an

preferably using FlexBox?

body {
margin: 0px;

.height-100vh {
height: 100vh;

.center-aligned {
display: box;
display: flex;
box-align: center;
align-items: center;
box-pack: center;
justify-content: center;

.background-image {
position: relative;

.text {
position: absolute;

<section class="height-100vh center-aligned">
<img class="background-image" src="" />
<div class="text">SOME TEXT</div>

Answer Source

The layout can be achieved with flexbox and positioning properties. No changes to HTML.

.height-100vh {
    height: 100vh;
    display: flex;                    /* establish flex container */
    flex-direction: column;           /* stack flex items vertically */
    position: relative;               /* establish nearest positioned ancestor for
                                         absolute positioning */

.text {
    position: absolute;  
    left: 50%;                        /* horizontal alignment */
    top: 50%;                         /* vertical alignment */
    transform: translate(-50%, -50%); /* horizontal, vertical alignment fine tuning;
                                        explanation: */

Revised Codepen

The code above centers the text both vertically and horizontally over the image:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download