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

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

vagrant

How to setup a (or multiple) server/LAMP-stack inside a virtual machine for local development with Vagrant and PuPHPet

You know this: You need a new server, something to develop on, something to test on, something to put your

Going node.js at Netflix (Slides by Micah R of Netflix)

It’s awesome how node.js takes over the absolute AAA-level corporate world. Note that node.js is still an early alpha product

Frontend Ops Conf 2014 – Keynote by Alex Sexton: “Front End Operations”

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

php

A super-simple introduction into PHP namespaces (7min video)

Once again, Jesse of JREAM totally nails it right on the head. A super-simple introduction into PHP namespaces. If you

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

git-php-deployment

Extremely simple deployment with PHPloy

Let me ask you a question: How mad do you get when you have to remember which files you edited

vagrant

How to setup a local server (in a virtual machine) with Vagrant in PHPStorm

This is part 1 of a series on How to get a modern workflow in PHP development. Part 2 is

sass

New features in SASS 3.3 (a talk by SASS-creator Chris Eppstein)

A very interesting conference talk by Chris Eppstein, creator of SASS itself, showing some of the new features in SASS

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

1/4

Categories

Search

Google I/O 2014 – HTTPS Everywhere (video)
nginx php 5.5
[Link] Set up Nginx with PHP 5.5 easily
css3-chrome-font
[Link] Retinafy your Site / Device by Nijiko Yonskai
How major web companies (and banks) handle passwords quite wrong
php
Why Modern PHP is Awesome And How You Can Use It Today (Slides by Matt Stauffer)
phpstorm 7.0 php
How to debug code on a remote server (or in vagrant box) with PHPStorm
Symfony devs: Creator of Symfony framework is hiring (Cologne, Germany)!
hearthbleed-ssl-bug
A quick guideline on how to fix the Hearthbleed bug (and update OpenSSL) on Ubuntu
vagrant
How to copy Vagrant boxes (or duplicate them)
php ide
Sitepoint asks for your favourite PHP IDE – take part!
hiphop php
Vote for “Hack” for HipHop/HHMV support (future style PHP) in PHPStorm 8
A quick history of Comic Sans, the most wrongly used font ever
php
[Link] Excellent PHP best practices, 2014 style
sass
New features in SASS 3.3 (a talk by SASS-creator Chris Eppstein)
css
How to center a div vertically and horizontally (modern methods, without fixed size!)

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