How do you easily horizontally center a <div> using CSS?

CssHtml

Css Problem Overview


I'm trying to horizontally center a <div> block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div> element to be inline with rest of my page. I'll try to draw an example:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text

Css Solutions


Solution 1 - Css

In the case of a non-fixed width div (i.e. you don't know how much space the div will occupy).

#wrapper {
  background-color: green; /* for visualization purposes */
  text-align: center;
}
#yourdiv {
  background-color: red; /* for visualization purposes */
  display: inline-block;
}

<div id="wrapper">    
    <div id="yourdiv">Your text</div>
</div>

Keep in mind that the width of #yourdiv is dynamic -> it will grow and shrink to accommodate the text inside it.

You can check browser compatibility on Caniuse

Solution 2 - Css

In most browsers this will work:

div.centre {
  width: 200px;
  display: block;
  background-color: #eee;
  margin-left: auto;
  margin-right: auto;
}

<div class="centre">Some Text</div>

In IE6 you will need to add another outer div:

div.layout {
  text-align: center;
}

div.centre {
  text-align: left;
  width: 200px;
  background-color: #eee;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

<div class="layout">
  <div class="centre">Some Text</div>
</div>

Solution 3 - Css

margin: 0 auto;

as ck has said, min-width is not supported by all browsers

Solution 4 - Css

The title of the question and the content is actually different, so I will post two solutions for that using Flexbox.

I guess Flexbox will replace/add to the current standard solution by the time IE8 and IE9 is completely destroyed ;)

Check the current Browser compatibility table for flexbox

Single element

.container {
  display: flex;
  justify-content: center;
}

<div class="container">
  <img src="http://placehold.it/100x100">
</div>

Multiple elements but center only one

Default behaviour is flex-direction: row which will align all the child items in a single line. Setting it to flex-direction: column will help the lines to be stacked.

.container {
  display: flex;
  flex-direction: column;
}
.centered {
  align-self: center;
}

<div class="container">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   </p>
  <div class="centered"><img src="http://placehold.it/100x100"></div>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
</div>

Solution 5 - Css

If old browsers are not an issue, use HTML5 / CSS3. If they are, apply polyfills and still use HTML5 / CSS3. I assume that your div has no margins or paddings here, but they are relatively easy to account for. The code follows.

.centered {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

What this does is:

  1. Position the div relative to its container;
  2. Position the div's left boundary at 50% of its container width horizontally;
  3. Translate back horizontally by 50% of the div's own width.

It is easy to imagine this process to confirm that the div would be horizontally centered eventually. As a bonus, you can center vertically at no additional cost:

.centered-vertically {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

The advantage of this approach is that you don't have to do any counterintuitive stuff, such as considering your div a text of sorts, wrapping it in a (often semantically useless) additional container, or giving it a fixed width, which is not always possible.

Don't forget vendor prefixes for transform if needed.

Solution 6 - Css

.center {
   margin-left: auto;
   margin-right: auto;
}

Minimum width is not globally supported, but can be implemented using

.divclass {
   min-width: 200px;
}

Then you can set your div to be

<div class="center divclass">stuff in here</div>

Solution 7 - Css

CSS, HTML:

div.mydiv {width: 200px; margin: 0 auto}

<div class="mydiv">
    
    I am in the middle
    
</div>

Your diagram shows a block level element also (which a div usually is), not an inline one.

Of the top of my head, min-width is supported in FF2+/Safari3+/IE7+. Can be done for IE6 using hackety CSS, or a simple bit of JS.

Solution 8 - Css

You should use position: relative and text-align: center on the parent element and then display: inline-block on the child element you want to center. This is a simple CSS design pattern that will work across all major browsers. Here is an example below or check out the CodePen Example.

p {
  text-align: left;
}
.container {
  position: relative;
  display: block;
  text-align: center;
}
/* Style your object */

.object {
  padding: 10px;
  color: #ffffff;
  background-color: #556270;
}
.centerthis {
  display: inline-block;
}

<div class="container">

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>

  <span class="object centerthis">Something Centered</span>

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>
</div>

Solution 9 - Css

Please use the below code and your div will be in the center.

.class-name {
    display:block;
    margin:0 auto;
}

Solution 10 - Css

you can use margin: 0 auto on your css instead of margin-left: auto; margin-right: auto;

Solution 11 - Css

If you know the width of your div and it is fixed, you can use the following css:

margin-left: calc(50% - 'half-of-your-div-width');

where 'half-of-your-div-width' should be (obviously) the half of the width of your div.

Solution 12 - Css

After nine years I thought it was time to bring a new version. Here are my two (and now one) favourites.

Margin

Set margin to auto. You should know the direction sequence is margin: *top* *right* *bottom* *left*; or margin: *top&bottom* *left&right*

aside{
    display: block;
    width: 50px;
    height: 100px;
    background-color: green;
    float: left;
}

article{
    height: 100px;
    margin: 0 0 0 50px; /* 50px aside width */
    background-color: grey;
}

div{
  margin: 0 auto;
  display:block;
  width: 60px;
  height: 60px;
  background-color: blue;
  color: white;
}

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>           
                <div>The div</div>
        </article>
    </body>
</html>

Center: Depricated, don't use this!

Use <center></center> tags as a wrap around your <div></div>.

Example:

aside{
    display:block;
    background-color:green;
    width: 50px;
    height: 100px;
    float: left;
}

center{
    display:block;
    background-color:grey;
    height: 100px;
    margin-left: 50px; /* Width of the aside */
}

div{
    display:block; 
    width: 60px; 
    height: 60px; 
    background-color:blue;
    color: white;
}

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>
            <center>
                <div>The div</div>
            </center>
        </article>
    </body>
</html>

Solution 13 - Css

Add this class to your css file it will work perfectly steps to do:

  1. create this first

  2. add this to your css

    .center-role-form { width: fit-content; text-align: center; margin: 1em auto; display: table; }

Solution 14 - Css

.center {
  height: 20px;
  background-color: blue;
}

.center>div {
  margin: auto;
  background-color: green;
  width: 200px;
}

<div class="center">
  <div>You text</div>
</div>

JsFiddle

Solution 15 - Css

If your <div> has position: absolute you need to use width: 100%;

#parent {
    width: 100%;
    text-align: center;
}

    #child {
        display: inline-block;
    }

Solution 16 - Css

Here I add proper answer

You can use this snippet code and customize. Here I use 2 child block.This should show center of the page. You can use one or multiple blocks.

<html>
<head>
<style>
#parent {
	width: 100%;
	border: solid 1px #aaa;
	text-align: center;
	font-size: 20px;
	letter-spacing: 35px;
	white-space: nowrap;
	line-height: 12px;
	overflow: hidden;
}

.child {
	width: 100px;
	height: 100px;
	border: solid 1px #ccc;
	display: inline-block;
	vertical-align: middle;
}
</style>
</head>

<body>

<div class="mydiv" id="parent">


<div class="child">
Block 1
</div>
<div class="child">
Block 2
</div>

</div>
</body>
</html>

Solution 17 - Css

The best response to this question is to use margin-auto but for using it you must know the width of your div in px or %.

CSS code:

div{
    width:30%;
    margin-left:auto;
    margin-right:auto;
}

Solution 18 - Css

In your html file you write:

<div class="banner">
  Center content
</div>

your css file you write:

.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}

works for me.

Solution 19 - Css

Usage of margin-left:auto and margin-right:auto may not work in certain situations. Here is a solution what will always work. You specify a required width and than set a left-margin to a half of the remaining width.

    <div style="width:80%; margin-left:calc(10%);">
        your_html
    </div>

Solution 20 - Css

I use div and span tags together with css properties such as block, cross-browser inline-block and text-align center, see my simple example

<!DOCTYPE html>
<html>
    <head>
       <title>Page Title</title>
       <style>
           .block{display:block;}
           .text-center{text-align:center;}
           .border-dashed-black{border:1px dashed black;}
           .inline-block{
                 display: -moz-inline-stack;
                 display: inline-block;
                 zoom: 1;
                 *display: inline;
            }
           .border-solid-black{border:1px solid black;}
           .text-left{text-align:left;}
        </style>
    </head>
    <body>
          <div class="block text-center border-dashed-black">
              <span class="block text-center">
	              <span class="block"> 
        <!-- The Div we want to center set any width as long as it is not more than the container-->
		              <div class="inline-block text-left border-solid-black" style="width:450px !important;">
		                     jjjjjk
		              </div> 
	              </span>
              </span>
          </div>
      </body>
   </html>

Solution 21 - Css

Using jQuery:

$(document).ready(function() {
	$(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
	$(".myElement_container_new").css({// for IE6
		"display" : "block",
		"position" : "relative",
		"margin" : "0",
		"padding" : "0",
		"border" : "none",
		"background-color" : "transparent",
		"clear" : "both",
		"text-align" : "center"
	});
	$(".myElement").css({
		"display" : "block",
		"position" : "relative",
		"max-width" : "75%", // for example
		"margin-left" : "auto",
		"margin-right" : "auto",
		"clear" : "both",
		"text-align" : "left"
	});
});

or, if you want to center every element with class ".myElement":

$(document).ready(function() {
	$(".myElement").each(function() {
		$(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
		$(".myElement_container_new").css({// for IE6
			"display" : "block",
			"position" : "relative",
			"margin" : "0",
			"padding" : "0",
			"border" : "none",
			"background-color" : "transparent",
			"clear" : "both",
			"text-align" : "center"
		});
		$(this).css({
			"display" : "block",
			"position" : "relative",
			"max-width" : "75%",
			"margin-left" : "auto",
			"margin-right" : "auto",
			"clear" : "both",
			"text-align" : "left"
		});
	});
});

Solution 22 - Css

you can use the position:relative; and then set the left and the top values:

.cenverDiv{
    position:relative;
    left:30%;
    top:0px;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncmcgintyView Question on Stackoverflow
Solution 1 - CssTivieView Answer on Stackoverflow
Solution 2 - CssAntony ScottView Answer on Stackoverflow
Solution 3 - CssRuss CamView Answer on Stackoverflow
Solution 4 - Cssm4n0View Answer on Stackoverflow
Solution 5 - Csswh1t3cat1kView Answer on Stackoverflow
Solution 6 - CsscjkView Answer on Stackoverflow
Solution 7 - CsssjhView Answer on Stackoverflow
Solution 8 - CssJoshua PekeraView Answer on Stackoverflow
Solution 9 - CssRiyazAhmedView Answer on Stackoverflow
Solution 10 - CsschicoxinView Answer on Stackoverflow
Solution 11 - CssP.PetkovView Answer on Stackoverflow
Solution 12 - CssOrryView Answer on Stackoverflow
Solution 13 - CssUrvashi BhattView Answer on Stackoverflow
Solution 14 - CssLexView Answer on Stackoverflow
Solution 15 - CssMarcio MazzucatoView Answer on Stackoverflow
Solution 16 - CssMohammad Shahnewaz SarkerView Answer on Stackoverflow
Solution 17 - CssAyman EL OuafiView Answer on Stackoverflow
Solution 18 - CsskrektoView Answer on Stackoverflow
Solution 19 - CssazakgaimView Answer on Stackoverflow
Solution 20 - Cssamachree tamunoemiView Answer on Stackoverflow
Solution 21 - CssRiccardo VolpeView Answer on Stackoverflow
Solution 22 - Cssgoli55View Answer on Stackoverflow