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
16

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 (10 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

16 Comments

  • Jose
    December 15, 2022 2:33 am

    Buenas tardes, encantado de saludarte. Soy Jose
    Quería escribirte porque me ha parecido interesante comentar contigo la posibilidad de que tu negocio aparezca cada mes en periódicos digitales como noticia para posicionar en los primeros lugares de internet, es decir, con artículos reales dentro del periódico que no se marcan como publicidad y que no se borran.
    La noticia es publicada por más de cuarenta periódicos de gran autoridad para mejorar el posicionamiento de tu web y la reputación.

    ¿Podrías facilitarme un teléfono para ofrecerte un mes gratuito?
    Gracias

    Reply
  • 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

php

PHP 5.6.0 RC1 is available

The first Release Candidate of PHP 5.6 is available here on php.net, as usual also for Windows systems. The RC

Frontend Ops Conf 2014 – Paul Irish: Delivering The Goods In Under 1000ms (40min video)

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

Meet the developers behind Ableton (14min video)

An excellent short documentation about the developers behind Ableton, the legendary creators of Ableton Live and Push. Without doubt, Live

Frontend Ops Conf 2014 – Rebooting Flickr On A Node.js Stack, One Page At A Time (from PHP) by Bertrand Fan

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

MINI, an extremely simple barebone PHP application

For my daily work I often needed to setup super-simple PHP applications, just some more or less static pages plus

Migrating Wikipedia to HHVM (@Scale Conference 2014)

Awesome topic, superfresh, directly from Scale Conference 2014. The title says everthing. Full quote from video’s description: As a top

php

Postmodern PHP: appserver.io, a multithreaded application server for PHP, written in PHP

There’s a lot of very interesting stuff going on in the PHP scene right now, I have the feeling this

Serious hard-to-fix bug in OAuth and OpenID discovered, lots of major sites affected

Just a short notice rather than a real article, full story later (I need to check the facts): Several sources

Create a fast, perfect and bootable 1:1 Windows backup (full clone of HDD) for SSD migration

In this article I want to share a super-simple, extremely fast and totally free workflow with you that will create

php-7

PHP 6.0 will be PHP 7

Germany’s excellent PHP Magazin just posted interesting news: The next major version of PHP will be PHP 7, the development

1/4

Categories

Search

composer
The difference between “composer install” and “composer update” – nailed on the head
MINI, an extremely simple barebone PHP application
phpstorm 7.0 php
How to setup and use XDEBUG with PHPStorm 6/7 (locally in Windows 7/8 and Mac OS X)
This is an experimental advertisement
nginx php 5.5
[Link] Set up Nginx with PHP 5.5 easily
Microsoft enters post-password era with Hello (promo video)
composer
A short & simple Composer tutorial
photoshop-cc-deal
Adobe offers Photoshop for $9.99 per month (limited deal)
DEF CON 18 – When your computer got stolen and you can still SSH into it: “Pwned by the 0wner” (22min conference talk)
Redesigning Windows 8 – fantastic and clever drafts by Jay Machalani
zend framework 3
First view on Zend Framework 3 by Matthew O’Phinney
Beautiful, minimal WordPress theme ZUKI by Elmastudio (with 30% discount)
phpstorm 7.0 php
PHPStorm 7 has been released!
github-logo-octocat
GitHub rolls out .PSD diff and viewing
Install Laravel 4 on Ubuntu 12.04 LTS (a how-to tutorial)

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”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
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