How to center content inside DIV using CSS (horizontal and vertical)

Posted by admin on Sun, 03/26/2017 - 13:29

Here's a collection of working solutions how to center content inside DIV horizontally and vertically (multiline text, image or anything) using CSS.

As an example we will use an image with multiline text to test.

<div class="center-wrapper">
  <div class="center-content">
    <img src="/images/placeholder/200x100.jpg" />
    <br/>This is a multiline text!
    <br/>It should be centered well!
  </div>
</div>

So, here's the list of solutions.

1. Using transform and translateX/translateY

.center-wrapper {
  position: relative;
}
.center-content {
  position: relative;
  top: 50%;
  transform: translateY(-50%); 
}

DEMO:



This is a multiline text!
It should be centered well!

2. Using flexbox

.center-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  flex-direction: column;
}

DEMO:


This is a multiline text!
It should be centered well!

PS. Flexbox is supported only in modern browsers.

3. Using table-cell method

.center-wrapper {
  display: table;
  text-align: center;
}
.center-content {
  display: table-cell;
  vertical-align: middle;
}

DEMO:


This is a multiline text!
It should be centered well!
Tags: 
×

Hey! Don't miss a new cool stuff!

Add new comment