Logo
  • PHP
    • HipHop / HHVM
    • Modern PHP
    • PHPStorm
    • LAMP
    • Laravel
    • Composer
    • PDO
  • JavaScript
    • node.js
    • AngularJS
  • CSS
    • SASS
    • “CSS4” (CSS level 4)
  • HTML
  • Git
  • LAMP
  • Vagrant
  • UI / UX
  • Architecture of …
  • Off-Topic
With ♥ from Berlin
September 26, 2013
Chris
CSS
15

How to center a div vertically and horizontally (modern methods, without fixed size!)

PreviousNext
css

“How to center a div” (inside another div or inside the body itself) is one of the most discussed questions ever, and to my surprise there are masses of tutorials which totally over-complicated this issue, usually also with lots of disadvantages, like a fixed height and width of the content div. However, there’s a simple, non-hacky, clean, responsive-ready and crossbrowser-safe method that also does not need any fixed pixel size div settings:

  1. Totally crossbrowser-safe. Works in all browsers (IE8 and higher).
  2. Totally liquid, no div size needed
  3. Totally clean, no weird hacks. All code is used the way it should be used.

 

Method 1:
Center a div in the middle of the viewport

CSS

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table;
}
.container {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    background-color: red; /* just for the demo */
    display: inline-block;
    text-align: left;
}

HTML

<div class="container">
    <div class="content">
        content content content 
        <br/>
        moooooooooooooooore content
        <br/>
        another content
    </div>
</div>

Result

center-a-div-horizontally-and-vertically

See the JSFiddle here: http://jsfiddle.net/panique/pqDQB/35/

 

Method 2:
Center div vertically and horizontally inside an other div

This is very useful for situation when you have to center content inside a div that don’t have a certain pixel size. Please note that this really doesn’t need ANY pixel size definition. For demo purposes we give the parent div demo pixel sizes, just to create a visible example.

CSS

.parent {
    display: table;
    /* optional, just for the demo */
    height: 300px;
    background: yellow;  
}
.child {
    display: table-cell;
    vertical-align: middle;
    /* optional, just for the demo */
    background: red;	
}
.content {
    /* optional, just for the demo */
    background: blue;
}

HTML

XXX

Result

See the Pen baity by Panique (@Panique) on CodePen.

Related articles across the web

  • From Designer to Developer: A Brief Guide
  • uncss
  • Video: CSS Backgrounds
  • 15 Captivating Parallax Effects from CodePen
  • Using CSS4’s validity pseudo-classes to make forms epic.
  • Use Upcoming CSS4 Features Right Now
  • Add CSS image-orientation: from-image
This article was written quite a while ago (9 years), please keep this in mind when using the information written here. Links, code and commands might be outdated or broken.

Random articles

  • Angelina Fabbro talks about “CSS4” in this excellent conference videoAngelina Fabbro talks about “CSS4” in this excellent conference video
  • Adobe releases Firebug-like developer tools to edit and extract PSDsAdobe releases Firebug-like developer tools to edit and extract PSDs
  • [Link] Improving Smashing Magazine’s Performance: A Case Study[Link] Improving Smashing Magazine’s Performance: A Case Study
  • Beautiful, minimal WordPress theme ZUKI by Elmastudio (with 30% discount)Beautiful, minimal WordPress theme ZUKI by Elmastudio (with 30% discount)
  • Jonathan Snook – CSS is a Mess – How to organize CSS in big projects (54min video talk)Jonathan Snook – CSS is a Mess – How to organize CSS in big projects (54min video talk)
  • 8 awesome pure CSS spinner / loader8 awesome pure CSS spinner / loader
  • [Link] Retinafy your Site / Device by Nijiko Yonskai[Link] Retinafy your Site / Device by Nijiko Yonskai
  • A quick video introduction into Shadow-DOM, the game-changing DOM-subtree-technologyA quick video introduction into Shadow-DOM, the game-changing DOM-subtree-technology
  • An introduction into Atomic Design, a super-clean way to style web applicationsAn introduction into Atomic Design, a super-clean way to style web applications
CSSCSS3
Share this

15 Comments

  • Ihor Kalashnikov
    March 24, 2016 7:13 pm

    Thank you, very usefull

    Reply
  • Anuj
    February 5, 2016 9:51 am

    exactly wt i was looking for ..you saved my ass ..ty

    Reply
  • chai
    April 21, 2015 7:06 am

    it only works in IE11

    Reply
  • Andy
    October 15, 2014 12:31 pm

    I dropped a key word in my comment – meant to say “I just used a element inside a

    Reply
  • Andy
    October 15, 2014 12:29 pm

    I tried to implement the solution in this article within an existing structured page but adding the display:table and display:table-cell ‘hacks’ just messed up my layout.

    I just used a element inside a and that did the job just fine. Why hack a div to misbehave when you can just use span out the box ?!

    Reply
  • Kiwitrix
    September 24, 2014 11:01 pm

    Thanks! Clean and simple.

    Reply
  • Arsh
    July 27, 2014 10:07 pm

    **I have been using the following solution (with no positioning and no line height) since over a year, it works with IE 7 and 8 as well.**

    .outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
    }

    .outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
    }

    .outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
    }

    .verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
    }

    Line 1
    Line 2

    Reply
    • Chris
      July 27, 2014 10:26 pm

      Okay, but this article is about when you DON’T have the height/width.

      Reply
  • Dell Mercant
    May 6, 2014 8:41 am

    faster way…

    .exactCenter {
    width:200px;
    height:200px;
    position: fixed;
    background-color: #00FF00;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    }

    More about….Div on center of page

    bradny

    Reply
    • Chris
      May 6, 2014 11:32 am

      Please note: This article is about NON-FIXED size divs! Especially for responsive and liquid sites it’s quite often not possible to give a size.

      Reply
  • Dave
    March 27, 2014 4:02 pm

    It seems i have to run in quirks mode in IE to get it to work there.

    Reply
  • Joaquin Rotharmel
    February 1, 2014 12:27 am

    Genius! Thanks!

    Reply
  • Brian
    November 26, 2013 7:18 pm

    Thank you very much! I like this method even though I hate using tables. Old technology still serves a purpose.

    Reply
    • Chris
      November 26, 2013 8:23 pm

      Thanks, but I would like to add that display: table-cell; was first introduced in 2010 (!), so it’s a very new technology, not an old one. Class tables are something totally different.

      Reply

Leave A Comment Cancel reply

The New Era of JavaScript (28min conference talk, Jack Franklin, 2013)

This article was written quite a while ago (8 years), please keep this in mind when using the information written

PHPStorm: 42 Tips and Tricks (47min video talk by Mikhail Vink at Dutch PHP Conference 2015)

To be honest I’ve not seen the clip yet, but it sounds so awesome and everybody is upvoting it. Have

steam sale coupon voucher

-30% to -90% on Steam and Origin

Soft off-topic, but as most developers like to play from time to time, this might be your change to grab

How to fix the ugly font rendering in Google Chrome

Update, August 2014: Google has rolled out Chrome 37, which finally fixes this issue nativly. Yeah! For historical reasons the

Support FLARUM, the future of PHP forum scripts (with some dollars on Kickstarter)

PHP forum scripts are horrible, let’s face it. Nearly everything that’s available is hard to install, hard to handle, hard

Creators of Laravel launch one-click-installations of Laravel (including nginx, PHP 5.5 etc.)

Again, a game changer: Taylor Otwell, creator of Laravel (which is currently the most popular PHP framework), has released FORGE

phpstorm 7.0 php

A perfect video tutorial to get started with xdebug in PHPStorm

Laracast just published an excellent short tutorial on how to get install xdebug in a local environment and how to

php uk conference

PHP Opcache Explained by Julien Pauli (video from PHP UK Conference 2014)

The title says it all. A VERY deep explanation on how OpCache works. If you never heard of this excellent

github-logo-octocat

GitHub buys Easel.io, a code-free full website creator worth a look

GitHub has just aquired Easel.io (which is NOT easel.ly who offer something similar for infographics / powerpoint !), a powerful

the-php-login-project

How to install php-login-one-file on Ubuntu 12.04 LTS

This tutorial will show you how to install the one-file version of php-login.net‘s login script (see the full GitHub repository

1/4

Categories

Search

ubuntu-14.04-lts
First view: Ubuntu 14.04 LTS brings PHP 5.5 and Apache 2.4
phpstorm-8
Ignore .idea folder from git in PHPStorm
php
Redesigning the PHP logo – who wants ?
Frontend Ops Conf 2014 – Paul Irish: Delivering The Goods In Under 1000ms (40min video)
phpstorm-github-code-color-syntax-theme
Get Github’s code colors in PHPStorm (2014 style)
How to setup a config-free WordPress, PHP and MySQL (for local development) in Windows 7 / 8 in under 3 minutes
php
Test out PHP 5.6alpha1 on Windows 7 / 8 with two clicks
mod-rewrite-ubuntu-14-04-lts
How to install / setup PHP 5.5.x on Ubuntu 12.04 LTS
How major web companies (and banks) handle passwords quite wrong
hiphop php
[Link] How to set up HipHop, Nginx and Laravel in Ubuntu 12.04 LTS (in a Vagrant box)
Create a fast, perfect and bootable 1:1 Windows backup (full clone of HDD) for SSD migration
php mvc
Preview-release of (my) “php-mvc” project (a simple php mvc barebone)
mod-rewrite-ubuntu-14-04-lts
How to enable mod_rewrite in Ubuntu 12.04 LTS
battlefield-3-free
Electronic Arts / Origin offers Battlefield 3 for free (limited promo action) !
cheap cloud server php
DigitalOcean rolls out interesting feature: Transfering server snapshots directly to the client’s account

Tags

apache bash centos composer conference coupon CSS debian fonts framework git GitHub hack HHVM HipHop HTML HTML5 IDE JavaScript JS LAMP laravel linux mod_rewrite MVC MySQL Nginx optimization PHP PHP 5.5 PHP 5.6 phpmyadmin PHPStorm security server SSD Ubuntu UI UX vagrant video virtual machine voucher VPS wordpress
Side-Project: Wordle-Solver:
www.wordle-helper.info

Pages

  • Privacy Policy
 
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT