- How can I horizontally center an element?
- 130 Answers 130
- The old box model (deprecated)
- The modern box model with Flexbox
- Read more about centering the child elements
- Centering a div of unknown height and width
- CSS Layout — Horizontal & Vertical Align
- Example
- Center Align Text
- Example
- Center an Image
- Example
- Left and Right Align — Using position
- Example
- Left and Right Align — Using float
- Example
- The clearfix Hack
- Without Clearfix
- With Clearfix
- Example
- Center Vertically — Using padding
- Example
- Example
- Center Vertically — Using line-height
- Example
- Center Vertically — Using position & transform
- Example
- Center Vertically — Using Flexbox
- Example
- How to align an inline-block horizontally and vertically
- 4 Answers 4
How can I horizontally center an element?
Of those great answers, I just want to highlight that you must give «#inner» a «width», or it will be «100%», and you can’t tell if it’s already centered.
display:flex; is the easiest to remember (Chrome gives you guides in DevTools) and supports centering on both axes.
130 Answers 130
With flexbox it is very easy to style the div horizontally and vertically centered.
To align the div vertically centered, use the property align-items: center .
Other Solutions
You can apply this CSS to the inner :
Of course, you don’t have to set the width to 50% . Any width less than the containing will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
It will make the inner element center horizontally and it works without setting a specific width .
You also set the top and bottom margins to 0, which is unrelated. Better putting margin-left: auto; margin-right: auto I think.
To support mobile browsers, I do not recommend using width: 50% . Use something like max-width: 300px instead.
voted most but not a better solution. the best way to do this is to use the combination of div and span tag, block css property and cross browser inline-block, and text center will do the simple magin
If you don’t want to set a fixed width on the inner div you could do something like this:
That makes the inner div into an inline element that can be centered with text-align .
@SabaAhang the correct syntax for that would be float: none; and is probably only needed because #inner has inherited a float of either left or right from somewhere else in your CSS.
This is a nice solution. Just keep in mind that inner will inherit text-align so you may want to set inner’s text-align to initial or some other value.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack , box-align , box-orient , box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
Read more about centering the child elements
And this explains why the box model is the best approach:
Safari, as of now, still requires -webkit flags for flexbox ( display: -webkit-flex; and -webkit-align-items: center; and -webkit-justify-content: center; )
I always think that use lots code is bad practice for example with this code I center my div: display: table; margin: auto; simple and easy
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don’t know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
The principle is still the same; put the item in the middle and compensate for the width.
I don’t like this solution because when the inner element is too broad for the screen, you can’t scroll over the whole element horizontally. margin: 0 auto works better.
The default width for most block level elements is auto, which fills the available area on screen. Just being centered places it in the same position as left alignment. If you wish it to be visually centered you should set a width (or a max-width although Internet Explorer 6 and earlier do not support this, and IE 7 only supports it in standards mode).
I’ve created this example to show how to vertically and horizontally align .
The code is basically this:
And it will stay in the center even when you resize your screen.
+1 for this method, I was about to answer with it. Note that you must declare a width on the element you wish to center horizontally (or height if centering vertically). Here’s a comprehensive explanation: codepen.io/shshaw/full/gEiDt. One of the more versatile and widely-supported methods of centering elements vertically and/or horizontally.
You cannot use padding within the div, but if you want to give the illusion use a border of the same color.
Some posters have mentioned the CSS 3 way to center using display:box .
This syntax is outdated and shouldn’t be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
. and you want to center your items within the box, here’s what you need on the parent element (.box):
.box < display: flex; flex-wrap: wrap; /* Optional. only if you want the items to wrap */ justify-content: center; /* For horizontal alignment */ align-items: center; /* For vertical alignment */ >* < margin: 0; padding: 0; >html, body < height: 100%; >.box < height: 200px; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; border: 2px solid tomato; >.box div < margin: 0 10px; width: 100px; >.item1 < height: 50px; background: pink; >.item2 < background: brown; height: 100px; >.item3
If you need to support older browsers which use older syntax for flexbox here’s a good place to look.
The Flexbox specification has gone through 3 major revisions. The most recent draft is from Sept 2012, which officially deprecates all previous drafts. However, browser support is spotty (particularly old Android browsers): stackoverflow.com/questions/15662578/…
Isn’t the «justify-content: center;» for the vertical alignment and the «align-items: center;» for the horizontal alignment?
@WouterVanherck it depends on the flex-direction value. If it is ‘row’ (the default) — then justify-content: center; is for the horizontal alignment (like I mentioned in the answer) If it is ‘column’ — then justify-content: center; is for the vertical alignment.
If you don’t want to set a fixed width and don’t want the extra margin, add display: inline-block to your element.
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
This works with any content
Tinker with it further on Codepen or on JSBin.
This is the only one that works for perfect centering and will remain centered even after the contents in the div are modified.
It’s a nice trick, but there is a little caveat. If the element has inline content that’s wider than 50% of the parent’s width, then the extra 50% offset from the left will extrapolate the parent’s width, breaking the content to the next lines to avoid overflow. But it’s possible to keep the content inline by setting in the centered element the white-space attribute to nowrap . Try that in this JSFiddle.
Set the width and set margin-left and margin-right to auto . That’s for horizontal only, though. If you want both ways, you’d just do it both ways. Don’t be afraid to experiment; it’s not like you’ll break anything.
It cannot be centered if you don’t give it a width. Otherwise, it will take, by default, the whole horizontal space.
The way I usually do it is using absolute position:
The outer div doesn’t need any extra properties for this to work.
I recently had to center a «hidden» div (i.e., display:none; ) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn’t necessary to display.)
NOTE: I’m sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don’t have any width and can’t be resized/centered until after they are displayed.
For Internet Explorer, Firefox, and Chrome:
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
CSS Layout — Horizontal & Vertical Align
Setting the width of the element will prevent it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
This div element is centered.
Example
Note: Center aligning has no effect if the width property is not set (or set to 100%).
Center Align Text
To just center the text inside an element, use text-align: center;
Example
Tip: For more examples on how to align text, see the CSS Text chapter.
Center an Image
To center an image, set left and right margin to auto and make it into a block element:
Example
Left and Right Align — Using position
One method for aligning elements is to use position: absolute; :
In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.
Example
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Left and Right Align — Using float
Another method for aligning elements is to use the float property:
Example
The clearfix Hack
Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the «clearfix hack» to fix this (see example below).
Without Clearfix
With Clearfix
Then we can add the clearfix hack to the containing element to fix this problem:
Example
Center Vertically — Using padding
There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding :
Example
To center both vertically and horizontally, use padding and text-align: center :
I am vertically and horizontally centered.
Example
Center Vertically — Using line-height
Another trick is to use the line-height property with a value that is equal to the height property:
I am vertically and horizontally centered.
Example
.center <
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
>
/* If the text has multiple lines, add the following: */
.center p line-height: 1.5;
display: inline-block;
vertical-align: middle;
>
Center Vertically — Using position & transform
If padding and line-height are not options, another solution is to use positioning and the transform property:
I am vertically and horizontally centered.
Example
.center <
height: 200px;
position: relative;
border: 3px solid green;
>
.center p margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
>
Tip: You will learn more about the transform property in our 2D Transforms Chapter.
Center Vertically — Using Flexbox
You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:
Example
.center <
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
>
Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.
How to align an inline-block horizontally and vertically
What is the best/cleanest using CSS to align the #dates div to the right side of the header, and vertically in the middle. I tried float: right , but that does not allow the vertical-align . I want to avoid using floats, so I am using inline-block , and using relative positioning. Is there a more correct approach? I do not like the fact that I have to do a top of 30px, and using trial and error until it centers.
2 Ramadhaan, 1435 AH Sunday 29 June 2014 #header < background-color: white; padding: 15px; position: relative; >#logo < display: inline-block; vertical-align: middle; >#logo img < vertical-align: bottom; /* to get rid of text descender space underneath image */ >#dates < display: inline-block; position: absolute; right: 30px; top: 30px; font-size: 14px; font-family: 'Open Sans'; color: #696969; background: url(Images/Interface/date-icon.png) no-repeat; background-position-y: center; padding-left: 32px; >
4 Answers 4
You can make use of css display:table :
You may need to give the #dates a width if you want it to be aligned to the right
CSS tables have advantages for this application. It might help to have a sub-wrapper div around the text block in the right hand table cell, that way you can use text-align right, and no need to worry about the exact table-cell width.
Using Inline-Blocks
Using your HTML elements as posted, try the following CSS:
#header < background-color: yellow; padding: 15px; text-align: justify; line-height: 0; >#logo < display: inline-block; vertical-align: middle; >#logo img < vertical-align: bottom; /* to get rid of text descender space underneath image */ >#dates < display: inline-block; line-height: 1.5; font-size: 14px; font-family:'Open Sans'; color: black; background-image: url(http://placehold.it/100x100); background-position: center; padding-left: 32px; >#header:after
Since you have two child elements in #header , a left logo image and a right text block, just use text-align: justify to force the logo to the left and the text to the right.
To get this to work, you need at least two rows in the #header .
To generate a second row, use a pseudo element: #header:after which will place a 100% wide empty inline-block after the date. The width: 100% forces it to start and fill a 2nd row and the vertical-align: top gets rid of the extra white space below the baseline.
To deal with the white space in the height, set line-height: 0 in #header which will allow the height of the pseudo-element to collapse to 0. However, you need to reset the line-height: 1.5 in #dates to get legible text.
Pros and Cons
With this approach, the elements will eventually wrap to two lines as the page width gets smaller.
If you want to keep the elements on a single line, you might be better off using CSS tables.