- How can I vertically center a div element for all browsers using CSS?
- 48 Answers 48
- Centering only vertically
- The outer container:
- The inner container:
- The content box:
- Demo:
- Centering horizontally and vertically
- The inner container:
- The content box:
- Demo:
- Centre aligning a div using viewport coordinates
- 2 Answers 2
- Viewport
- case 1
- case 2
How can I vertically center a div element for all browsers using CSS?
I want to center a div vertically with CSS. I don’t want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.
Div to be aligned vertically
48 Answers 48
Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and worked for recent versions of Firefox, Opera, Chrome, and Safari.
The Content
Once upon a midnight dreary.
I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also — lightbox, pop-up, etc.
The simplest way would be the following three lines of CSS:
1) position: relative;
3) transform: translateY(-50%);
Following is an example:
I had found this solution elsewhere first, but extra kudos to this particular answer for mentioning the -webkit-transform variant in particular, which I needed to make this method work in phantomjs. ended hours of struggling so thank you!
This is the best answer. This is incredibly simple, messes with the least amount of existing work and functions on everything as far back as IE9 which nobody even uses anymore. Lets get this guy some more upvotes!
One more I can’t see on the list:
.Center-Container < position: relative; height: 100%; >.Absolute-Center
- Cross-browser (including Internet Explorer 8 — Internet Explorer 10 without hacks!)
- Responsive with percentages and min-/max-
- Centered regardless of padding (without box-sizing!)
- height must be declared (see Variable Height)
- Recommended setting overflow: auto to prevent content spillover (see Overflow)
Now the Flexbox solution is a very easy way for modern browsers, so I recommend this for you:
Div to be aligned vertically
If you’ve got a navbar , you can tweak the height using height: calc(100% — 55px) or whatever the height of your navbar is.
Please note that this will potentially behave weird on «newer older» mobile safari browsers. The recommended use instead of height is flex-basis on the .container class
Actually, you need two div’s for vertical centering. The div containing the content must have a width and height.
Edit 2020: only use this if you need to support old browsers like Internet Explorer 8 (which you should refuse to do 😉). If not, use Flexbox.
This is the simplest method I found and I use it all the time (jsFiddle demo here).
Thank Chris Coyier from CSS Tricks for this article.
html, body < height: 100%; margin: 0; >.v-wrap < height: 100%; white-space: nowrap; text-align: center; >.v-wrap:before < content: ""; display: inline-block; vertical-align: middle; width: 0; /* adjust for white space between pseudo element and next sibling */ margin-right: -.25em; /* stretch line height */ height: 100%; >.v-box
This is how I've been doing it for some time
Support starts with Internet Explorer 8.
Refusing support for old browsers, the solution for me was not flexbox but grid system. It was a bit annoying for me center content in a container that, when it becames too small in height, needed to show scrollbar, and the centered content was loosing out the scroll area with all other methods. In the container i just use: < display: grid; align-items: center; >Hope this helps someone.
After a lot of research I finally found the ultimate solution. It works even for floated elements. View Source
This does works really well, provided you remember that the container element must have an implicit or explicit height; jsfiddle.net/14kt53un A minor gotcha to those who are relatively new to CSS.
Out of all the answers, this is the most simplest! I hope others see your answer too! Thank you! By the way, 50% worked for me (not -50% )
That was incredible. After hours of searching, this one worked for me. I had to use translateY(50%) I am sure why, but it worked. In my case, the parent was created by AEM Forms Engine, and I can only control certain child elements.
This is centered vertically
To center the div on a page, check the fiddle link.
Div to be aligned vertically
Another option is to use flex box, check the fiddle link.
Div to be aligned vertically
Another option is to use a CSS 3 transform:
Div to be aligned vertically
@ArmelLarcier That’s incorrect. Relative units are percentages % , em s and rem s. Absolute or fixed values are pixels or points. What you’re referring to is «it only works with a declared height». Howevever, although this method described by Moes does require a height, when you declare it in relative units, percentage is the best, no matter how much content is inside the centered DIV that DIV will expand vertically to fit its content. That’s the beauty of this method. The other good thing is that this method works in IE8/9/10 in case someone still needs to support those browsers.
@ricardozea I don’t mean to play stubborn but saying the centered div will expand vertically while remaining vertically centered is wrong. Try it. I know when I say the height must be «fixed», that it’s not the right word. It is indeed relative, to its parent. Anyway I think Chris Coyer’s method makes more sense, see my answer stackoverflow.com/a/21919578/1491212 It’s compatible with IE8 AND does work on an element with no specified dimensions.
@ArmelLarcier It’s all good. Is not wrong brother. Try it: codepen.io/shshaw/pen/gEiDt — Add paragraphs to the green box ;]. Granted, it uses Modernizr to accomplish the effect, but all in all it’s doable. I saw your answer and the CSS-Tricks.com post as well, but that method doesn’t make me happy, it uses extra markup and the CSS is too verbose. I think the best solution is either using flexbox or the transform: translate(-50%, -50%); technique. For IE8 I’d just leave it top/center aligned and move on.
@ricardozea Well the codepen you linked to uses the «display: table» method and extra markup so I’m not surprised. Anyways, +1 to your last sentence.
The easiest solution is below:
There are multiple ways to achieve this.
Using flex property of CSS.
or by using display: flex; and margin: auto;
show text center
Using percentage(%) height and width.
Unfortunately — but not surprisingly — the solution is more complicated than one would wish it to be. Also unfortunately, you’ll need to use additional divs around the div you want vertically centered.
For standards-compliant browsers like Mozilla, Opera, Safari, etc. you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%. The following pages explain this technique well and provide some code samples too:
There is also a technique to do the vertical centering using JavaScript. Vertical alignment of content with JavaScript & CSS demonstrates it.
If someone cares for Internet Explorer 10 (and later) only, use Flexbox:
@t.mikael.d You might want to take a closer look at that table. For Android < 4.4, it states "Only supports the old flexbox specification and does not support wrapping."
A modern way to center an element vertically would be to use flexbox .
You need a parent to decide the height and a child to center.
The example below will center a div to the center within your browser. What’s important (in my example) is to set height: 100% to body and html and then min-height: 100% to your container.
body, html < background: #F5F5F5; box-sizing: border-box; height: 100%; margin: 0; >#center_container < align-items: center; display: flex; min-height: 100%; >#center
.center < position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* (x, y) =>position */ -ms-transform: translate(-50%, -50%); /* IE 9 */ -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ > .vertical < position: absolute; top: 50%; //left: 0; transform: translate(0, -50%); /* (x, y) =>position */ > .horizontal < position: absolute; //top: 0; left: 50%; transform: translate(-50%, 0); /* (x, y) =>position */ > div
Vertically left Horizontal top Vertically Horizontal
Centering only vertically
If you don’t care about Internet Explorer 6 and 7, you can use a technique that involves two containers.
The outer container:
The inner container:
The content box:
You can add any content you want to the content box without caring about its width or height!
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; >.centered-content
Centering horizontally and vertically
If you want to center both horizontally and vertically, you also need the following.
The inner container:
The content box:
- should re-adjust the horizontal text-alignment to for example text-align: left; or text-align: right; , unless you want text to be centered
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
It can be done in two ways
align-items:center; makes the content vertically center
justify-content: center; makes the content horizontally center
This is always where I go when I have to come back to this issue.
For those who don’t want to make the jump:
- Specify the parent container as position:relative or position:absolute .
- Specify a fixed height on the child container.
- Set position:absolute and top:50% on the child container to move the top down to the middle of the parent.
- Set margin-top:-yy where yy is half the height of the child container to offset the item up.
An example of this in code:
#myoutercontainer #myinnercontainer . Hey look! I'm vertically centered!
How sweet is this?!
I just wrote this CSS and to know more, please go through: This article with vertical align anything with just 3 lines of CSS.
CSS transforms can cause distortions in text and borders (when the math results in fractional pixels).
display: flex; align-items: center; justify-content: center;
I came across with this wonderful explanation of align items and justify content. Must Read : stackoverflow.com/questions/42613359/…
The three lines of code using transform works practically on modern browsers and Internet Explorer:
I am adding this answer since I found some incompleteness in the previous version of this answer (and Stack Overflow won’t allow me to simply comment).
- ‘position’ relative messes up the styling if the current div is in the body and has no container div. However ‘fixed’ seems to work, but it obviously fixes the content in the center of the viewport
- Also I used this styling for centering some overlay divs and found that in Mozilla all elements inside this transformed div had lost their bottom borders. Possibly a rendering issue. But adding just the minimal padding to some of them rendered it correctly. Chrome and Internet Explorer (surprisingly) rendered the boxes without any need for padding
Centre aligning a div using viewport coordinates
I am learning CSS , I am new to this field. Please excuse me if my questions is naive. I have a simple HTML containing 1 div .
I am expecting a margin of 5% of viewport width on both sides of the div . However, it seems that we have broader gap in the left side of div compared to right. I am not sure where these extra margin is coming from.
2 Answers 2
You can do this: Give max with and then subtract 10% (5% each side), then center square with margin auto.
Yes, I think we are getting a margin of 8px from User Agent style sheet. 8px margin is on both sides. However, still (if I don’t reset the margin of body and html to 0) left gap is around 69 pixel and right gap is 53 pixel. I measured it using taking a screenshot and using preview app on mac.
Certainly, if you are using only viewport measure you will get sizes from view port. From left to right you will get 5vw + (Browser default margin) and then it will ignore the right margin because is not right in mathematic (margin 10vw + 90vw + browser margins). If you set your margin, use like my answer in percentage. this will make a better adjustments and good mathematic (viewport and in the fact the margins of the elements).
That was what I also suspected but I was not sure that browser will drop its user agent styles in these cases.
Since you said you are new to HTML & CSS, let me give you a breif description on how to adjest widht of an element based on the viewport.
Viewport
The viewport is the area of your browser where the actual content is displayed — in other words your web browser without its toolbars and buttons. The units are vw , vh , vmin and vmax . They all represent a percentage of the browser (viewport) dimensions and scale accordingly on window resize.
Lets say we have a viewport of 1000px (width) by 800px (height):
- vw — Represents 1% of the viewport’s width. In our case 50vw = 500px.
- vh — A percentage of the window’s height. 50vh = 400px.
- vmin — A percentage of the minimum of the two.
In our example 50vmin = 400px since we are in landscape mode. vmax — A percentage of the bigger dimension. 50vmax = 500px.
You can use these units anywhere that you can specify a value in pixels, like in width , height , margin , font-size and more. They will be recalculated by the browser on window resize or device rotation.
case 1
Now considering your issue, I don’t see any change in width on either side, because if you see your inspector->layout->margin I can see both sides showing 64 on the screenshot you provided.
case 2
If you really do see the change in your system again. Try removing the external CSS you have mentioned to see if that’s causing any issue and then put margin:0px for html and body.