Best way to center a <div> on a page vertically and horizontally? [duplicate]
Asked Answered
I

30

627

Best way to center a <div> element on a page both vertically and horizontally?

I know that margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?

Ionian answered 10/12, 2008 at 17:11 Comment(3)
Here's a simple, clean and stable way to center divs in a container using only CSS. https://mcmap.net/q/36332/-vertically-center-two-elements-within-a-div-duplicateTelevise
This question is marked as a duplicate of a question asked 5 years later. Oh StackOverflow.Workbag
margin-left: auto; margin-right: auto;Matronize
O
844

The best and most flexible way

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

##This trick will work with any sizes of div.

div {
    width: 100px;
    height: 100px;
    background-color: red;
    
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    
    margin: auto;
}
<div></div>
Orland answered 13/11, 2012 at 6:27 Comment(16)
This is awesome. I have wondered for so long how to do this. I had tried it with top: 0; and left: 0;, but it seems that the addition of bottom: 0; and right: 0; make the difference. Thank you.Selfassurance
@Prembo trick works everywhere except IE7Orland
This solution only works if your element has a fixed height. See tombul's answer for two solutions that do not change the element's natural height.Tractable
To escape nesting effects from any other DOM elements, you should use position:fixed;Anamorphosis
@Anamorphosis wat? can you explain?Orland
Doesn't work with dynamic contentDarees
I was going to say that it is the best, but I find annoying that you have to set fixed div dimentions. You can always use fixed margins to make it center (bad idea!!!). This solution (even thought it is mine) seems to be much better. I am just trying to be honest, and to lead other users to best solution, not the one that has most points because of time. Sorry, but -1... and I would give it -100 if I could, because it is sad that not the best answer has like 200+ points. Leading to misunderstandings.Guevara
@FlashThunder you suggest tables for non-table data, aren't you?Orland
@FlashThunder also my solution is not about fixed position, is about fixed box sizeOrland
Excellent! I did not even know bottom: and right: existed in css...Mistral
the background-color doesn't belong thereFillet
If your page scrolls (is higher or wider then the window) the div might scroll out of sight, position: fixed to make sure it stays in centered in the view port.Shechem
Must remember to write down margin:auto or else it don't take effects.Frederigo
Can also use position: fixed. It works with that also.,Vaclava
@Flo, inline code snippets preview work as good as dabbletOrland
is there any way to do this without using position: absolute? Absolute positioning is very rigid and isn't best practice especially due to the problems when you're shifting screen sizesGinglymus
P
163

Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flex or pseudo classes.

You can see an example in the following fiddle. Here is the updated fiddle.

For pseudo classes an example could be:

.centerPseudo {
    display:inline-block;
    text-align:center;
}

.centerPseudo::before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
    width:0px;
}

The usage of display: flex, according to css-tricks and MDN is as follows:

.centerFlex {
  align-items: center;
  display: flex;
  justify-content: center;
}

There are other attributes available for flex, which are explained in above mentioned links, with further examples.

If you have to support older browsers, which don't support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.

Pademelon answered 4/9, 2013 at 15:43 Comment(1)
All browsers from 2012–2013 upwards support flex boxes. From today’s standpoint it should be safe enough to use it for new applications under most circumstances. The only situation I can think of where the older model should be preferred are business customers who rely on older infrastructure and can’t upgrade.Hertel
B
117

Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it's just fine. Use with care)

Markup:

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>

And CSS:

div {
  color: white;
  background: red;
  padding: 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}   

This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?

Brammer answered 16/1, 2015 at 16:3 Comment(4)
Yes, I used a lot this method... but, problem come if element is much higher then screen height (where height is unknown) ... top of centered element would be cut. Even if element is putted in parent element where overflow is set to auto or scroll. Same problem using flex. Unfortunately, like last resort I use table to override this problem. Only when centered element will be much, much higher (dynamically populated).Draghound
I had to set position to relative, probably because my div floats right.Juanajuanita
Nelek - if parent element has fixed width and height you can add max-width:100% and max-height:100% to the image and prevent it from expanding the parentNidus
Please check it in box model. its not coming on center. its showing as center but its exact pixel values are not there.Gaslight
S
87

I would use translate:

First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50%). Then, translate moves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.

I actually think that this method is better than many of the others, since it does not require any changes on the parent element.

translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d

To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  
  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.


Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);

  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>
Shallow answered 19/4, 2016 at 11:42 Comment(1)
This has annoying side-effects when the box you want to centre has width or height greater than half of the viewport.Baryton
N
34

Using Flex-box in my opinion:

#parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="parent">
  <div id="child">Hello World!</div>
</div>

You see there are only three CSS properties that you have to use to center the child element vertically and horizontally. display: flex; Do the main part by just activating Flex-box display, justify-content: center; center the child element vertically and align-items: center; center it horizontally. To see the best result I just add some extra styles :

#parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  width: 500px;
  background: yellow;
}

#child {
  width: 100px;
  height: 100px;
  background: silver;
}
<div id="parent">
  <div id="child">Hello World!</div>
</div>

If you want to learn more about Flex-box you can visit W3Schools, MDN or CSS-Tricks for more information.

Nay answered 10/9, 2018 at 23:25 Comment(1)
thanks, this worked, amazing and simple to understand solution , and very detailed, keep answering !!Monde
M
33

Simple solution taking advantage of Flex Display

 <div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
      <div id = 'div_you_want_centered' style = 'margin:auto;'> 
           This will be Centered 
      </div>
 </div>

Check out http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The first div takes up the whole screen and has a display:flex set for every browser. The second div (centered div) takes advantage of the display:flex div where margin:auto works brilliantly.

Note IE11+ compatibility. (IE10 w/ prefix).

Moriahmoriarty answered 9/1, 2015 at 20:58 Comment(2)
Whoah... IE11+! No thank you!Guevara
I would suggest using auto-prefix when having many -webkit- in css :)Rocher
J
26

I think there are two ways to make a div center align through CSS.

.middleDiv {
    position : absolute;    
    width    : 200px;
    height   : 200px;
    left     : 50%;
    top      : 50%;
    margin-left : -100px; /* half of the width  */
    margin-top  : -100px; /* half of the height */
}

This is the simple and best way. for the demo please visit below link:

http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html

Judicature answered 6/7, 2013 at 11:37 Comment(0)
R
22

If you are looking at the new browsers(IE10+),

then you can make use of transform property to align a div at the center.

<div class="center-block">this is any div</div>

And css for this should be:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.

Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relative and then this CSS starts working for your div.

How it works:

When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page. This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).

But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.

If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.

Rolling answered 26/7, 2015 at 17:38 Comment(0)
A
16

My prefered way to center a box both vertically and horizontally, is the following technique :

The outer container

  • should have display: table;

The inner container

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

The content box

  • should have display: inline-block;
  • should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered

The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!

Demo

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        You can put anything here!
     </div>
   </div>
</div>

See also this Fiddle!


EDIT

Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%); or transform: translate3d(-50%,-50%, 0);, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit, -ms or -moz, transform doesn't offer quite the same browser support.

So if you care about older browsers (eg. IE9 and below), you should not use transform for positioning.

Advocate answered 25/2, 2016 at 23:22 Comment(3)
This only works if the page has a container div and is much more complex then translate.Shallow
@MDTech.us_MAN : While it is true that you need more HTML markup, this approach works even in pretty old browsers! Even with browsers prefixes like -webkit, -ms or -moz, transform: translate(-50%, -50%); doesn't have nearly the same browser support! → I added this info at the bottom of my answerAdvocate
I know, but its 2017 now and there really should not be that much of a concern... IE9 was released back in 2011. caniuse.com/#search=translate says that 95% of the internet should support transform.Shallow
T
16
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

Explanation:

Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.

Titrate answered 25/7, 2016 at 15:45 Comment(3)
Although this code may help to solve the problem, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.Palimpsest
But, if we also add width: 100% then, the width of that div will also preserve.Labellum
I face blur issue using this technique on some screens. is there any solution for that ?Suffragette
H
13

Here is a script i wrote a while back (it is written using the jQuery library):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};
Hazardous answered 10/12, 2008 at 17:16 Comment(3)
Sadly, OP did not ask for a JavaScript/jQuery solution.Scyphus
Isn't it better to use outerHeight(true) and outerWidth(true) instead of height() and width(), since "outer" takes account of all possible margin & paddingAlcoholize
Very handy when you don't know the height/width of the div in advance. :o)Greenheart
G
13

This is the best code to centre the div bot horizontally and vertically

div
{
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
}
Greenlet answered 28/7, 2017 at 11:43 Comment(0)
D
9

2018 way using CSS Grid:

.parent{
    display: grid;
    place-items: center center;
}

Check for browser support, Caniuse suggests it works from Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check myself.

See snippet below:

.parent{
    display: grid;
    place-items: center center;
    /*place-items is a shorthand for align-items and justify-items*/
    
    height: 200px;
    border: 1px solid black;
    background: gainsboro;
}

.child{
    background: white;
}
<div class="parent">
    <div class="child">Centered!</div>
</div>
Dallapiccola answered 28/1, 2018 at 10:15 Comment(1)
that is not centered at all in edgeLai
B
8

I know I am late to the party but here is a way to center a div with unknown dimension inside a parent of unknown dimension.

style:

<style>

    .table {
      display: table;
      height: 100%;
      margin: 0 auto;
    }
    .table-cell {
      display: table-cell;
      vertical-align: middle;      
    }
    .centered {
      background-color: red;
    }
  </style>

HTML:

<div class="table">
    <div class="table-cell"><div class="centered">centered</div></div>
</div>

DEMO:

Check out this demo.

Bauman answered 24/7, 2014 at 13:48 Comment(1)
I like it, but using real table feels to be "cleaner" and more valid - generates, although, a bit more code.Guevara
M
8

Though I'm too late, but this is very easy and simple. Page center is always left 50%, and top 50%. So minus the div width and height 50% and set left margin and right margin. Hope it work's for everywhere -

body{
  background: #EEE;
}
.center-div{
  position: absolute;
  width: 200px;
  height: 60px;
  left: 50%;  
  margin-left: -100px;
  top: 50%;
  margin-top: -30px;
  background: #CCC;
  color: #000;
  text-align: center;
}
<div class="center-div">
  <h3>This is center div</h3>
</div>
Mccallum answered 26/4, 2018 at 4:58 Comment(0)
H
6
div {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

Adjust left and top with respect to width and height, that is (100% - 80%) / 2 = 10%

Heda answered 22/7, 2014 at 11:45 Comment(0)
T
6

There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use transformY to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:

<div class="parent">
    <div class="center-me">
        Text, images, whatever suits you.
    </div>
</div>

.parent { 
    /* height can be whatever you want, also auto if you want a child 
       div to be responsible for the sizing */ 
    height: 200px;
}

.center-me { 
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* prefixes needed for cross-browser support */
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)

JS Fiddle Demo

Tenterhook answered 22/9, 2014 at 16:6 Comment(4)
Most browsers didn't fully support unitl novaday versions, thats why this solution (at least in my opinion) is totally usless, sorry.Guevara
Ehrm... I actually don't really understand what you're saying. As browsers "didn't" fully support, it was (not totally) useless imo. As current browsers (all major ones and IE9+) do fully support it, this is a viable solution right now, isn't it? Also checkout CanIUse.Tenterhook
This is an elegant solution that works with any sized content, even if the DIV element dimensions dynamically change (e.g. if you use jQuery to modify the contents and the DIV height has to readjust). HOWEVER, there are still bugs in some environments where using transform causes the text to appear blurry. Please take care in using this solution.Emigration
Thanks @BaoNgo, a valuable addition. Do you perhaps know in which kind of environments (browser? os? device?) this problem arises? I will alter the answer accordingly!Tenterhook
V
6

Solution

Using only two lines of CSS, utilizing the magical power of Flexbox

.parent { display: flex; }
.child { margin: auto }
Voletta answered 14/8, 2017 at 23:28 Comment(1)
Which version of CSS was the 'flex' display type added?Yugoslavia
B
5

One more method (bulletproof) taken from here utilizing 'display:table' rule:

Markup

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}
Brammer answered 9/10, 2014 at 15:44 Comment(2)
I know that it is the same comment as below, but it is simple duplicate answer, so... I like it, but using real table feels to be "cleaner" and more valid - generates, although, a bit more code.Guevara
@FlashThunder - update your knowledge (I got second answer with new technique utilizing transforms, underneath) and eventually stop using tables for layout ;)Brammer
W
5

I was looking at Laravel's view file and noticed that they centered text perfectly in the middle. I remembered about this question immediately. This is how they did it:

<html>
<head>
    <title>Laravel</title>

    <!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->

    <style>
        .container {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            display: table;

        }

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


    </style>
</head>
<body>
    <div class="container">
            <div class="inside">This text is centered</div>
    </div>
</body>

Result looks so:

enter image description here

Washy answered 24/3, 2015 at 20:19 Comment(1)
I guess it only works when it's the only thing. Add more div and other content, and it doesn't seem to work any more.Interlanguage
C
4

An alternative answer would be this.

<div id="container"> 
    <div id="centered"> </div>
</div>

and the css:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}
Cannell answered 11/12, 2014 at 14:16 Comment(2)
Solution only for IE9+ ... not that good ... +0Guevara
@FlashThunder "Solution only for IE9+ ... not that good ..." -- only if you insist on supporting a sub-1% of blatantly outdated -- and, for the most part, blatantly ignorant -- users. People who refuse to update for so long are already used to an infinitely broken web experience.Tinishatinker
I
4

I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes.
As you might know, total height of the viewport = 100vh.
Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically.
Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.

.container {
         width: 60vw; /*optional*/
         height: 60vh;
         margin: 20vh auto;
         background: #333;
 }
<div class="container">
</div>
Instantaneous answered 24/2, 2018 at 8:43 Comment(1)
Anytime you want to change height, you must recalculate margin, which is not very convenient. Also this won't work for elements with no fixed size and is tied to viewport height.Dallapiccola
E
3

If you guys are using JQuery, you can do this by using .position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript (JQuery)

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

JSFiddle : http://jsfiddle.net/vx9gV/

Electrophysiology answered 18/9, 2013 at 10:9 Comment(1)
OP asked for a CSS solution.Scyphus
E
3

In case you know a defined sized for your div you could use calc.

Live example: https://jsfiddle.net/o8416eq3/

Notes: This works only if you hard coded the width and height of your ``div` in the CSS.

#target {
  position:fixed;
  top: calc(50vh - 100px/2);
  left: calc(50vw - 200px/2);
  width:200px;
  height:100px;
  background-color:red;
}
<div id='target'></div>
Envy answered 16/6, 2016 at 11:59 Comment(1)
Way too complex. using translate is just simpler. No reason to use extra calcs and vw/vh.Shallow
W
3

Using display:grid on parent and setting margin:auto to the centrerd elemnt will do the trick :

See below snippet :

html,body {
  width :100%;
  height:100%;
  margin:0;
  padding:0;
}

.container {
  display:grid;
  height:90%;
  background-color:blue;
}

.content {
  margin:auto;
  color:white;
}
<div class="container">
  <div class="content"> cented div  here</div>
</div>
Watermark answered 17/8, 2017 at 8:39 Comment(0)
L
3

div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%); /* IE 9 */
    -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	    
}
<body>
    <div>Div to be aligned vertically</div>
</body>

position: absolute div in body document

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport (body tag), like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

source: CSS position

Lope answered 23/9, 2017 at 2:17 Comment(0)
R
2

Is the browser supports it, using translate is powerful.

position: absolute;
background-color: red;

width: 70%;     
height: 30%; 

/* The translate % is relative to the size of the div and not the container*/ 
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);
Ranchero answered 4/8, 2015 at 13:42 Comment(0)
M
0

Sorry for late reply best way is

  div {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -100px;
    }

margin-top and margin-left should be according to your div box size

Miquelon answered 16/10, 2013 at 14:58 Comment(1)
Shouldn't margins be in percent and 25% both? Sorry but this solution seems not to be working (at lest for now), -1Guevara
R
0

Please use following CSS properties for center align element horizontally as well as vertically. This is worked fine for me.

div {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
}
Robbirobbia answered 6/10, 2017 at 8:44 Comment(1)
This is almost the same as the top voted answer from five years ago. The major difference, this answer has no explanation.Rapids
Y
-1

This solution worked for me

    .middleDiv{
        position : absolute;
        height : 90%;
        bottom: 5%;
    }

(or height : 70% / bottom : 15%

height : 40% / bottom :30% ...)

Ygerne answered 24/8, 2012 at 14:3 Comment(1)
No it's not - it doesn't center element horizontally. It's half-solution to the problem.Brammer

© 2022 - 2024 — McMap. All rights reserved.