748

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
cmcginty
  • 113,384
  • 42
  • 163
  • 163

22 Answers22

824

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

Tivie
  • 18,864
  • 5
  • 58
  • 77
578

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>
YakovL
  • 7,557
  • 12
  • 62
  • 102
Antony Scott
  • 21,690
  • 12
  • 62
  • 94
62
margin: 0 auto;

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

Community
  • 1
  • 1
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 1
    Note that this only works when the element also has its `width` property set. When you want the element's width to be dynamic (based on its contents), see the chosen answer. – Niko Bellic Mar 07 '17 at 00:45
50

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>
m4n0
  • 29,823
  • 27
  • 76
  • 89
  • Yeah, Flexbox is the (not so) "modern" way of doing this :) – Tivie Aug 18 '17 at 13:02
  • Yeah. Care to edit this so that it can reach the general audience, Tivie? ;) – m4n0 Sep 02 '17 at 04:00
  • What do you mean? Your answer works perfectly – Tivie Sep 06 '17 at 20:39
  • Sorry. I misunderstood your comment. I thought you were pointing towards the description being old as I had quit coding for over 2 years and unaware of the current CSS trends. BTW What do you think? Do we need a better system than flexbox for the alignment? Since centering in CSS has been a hot topic for the last 20 years. – m4n0 Sep 08 '17 at 03:43
  • 2
    This worked for me when the top two answers didn't. Thank you. – Ellen Spertus Oct 01 '17 at 20:45
  • Glad it was helpful. It seems we need a major refresh of all our answers. – m4n0 Oct 01 '17 at 22:47
  • 1
    @ManojKumar I think flexbox "fixes" a lot of the design issues and is currently supported by almost every browser. – Tivie Dec 18 '17 at 08:47
  • 1
    For some reason margin: 0 auto, didn't work in my Bourbon Neat project, but flexbox saved the day. – Halfacht Jun 28 '18 at 22:13
35

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.

wh1t3cat1k
  • 3,146
  • 6
  • 32
  • 38
  • An issue with the horizontal method is that the centered element will not dynamically scale past 50% of the parent's width: https://jsfiddle.net/ywy9w3gk/ – user2145184 Dec 08 '16 at 17:53
30
.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>
Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
cjk
  • 45,739
  • 9
  • 81
  • 112
28

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.

Thomas Orlita
  • 1,554
  • 14
  • 28
sjh
  • 2,236
  • 1
  • 18
  • 21
  • Thanks for clarifying about the "inline" terminology. I was trying to say that I didn't want it to float over any text. – cmcginty Mar 06 '09 at 10:23
11

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>
Joshua Pekera
  • 525
  • 5
  • 8
10

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

.class-name {
    display:block;
    margin:0 auto;
}
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
RiyazAhmed
  • 115
  • 1
  • 2
  • 10
9

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

Kartoch
  • 7,610
  • 9
  • 40
  • 68
chicoxin
  • 128
  • 1
  • 10
8

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.

P.Petkov
  • 1,569
  • 1
  • 12
  • 20
5

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

1) create this first

<div class="center-role-form">
  <!--your div (contrent) place here-->
</div>

2) add this to your css

.center-role-form {
    width: fit-content;
    text-align: center;
    margin: 1em auto;
    display: table;
}
Urvashi Bhatt
  • 489
  • 5
  • 21
5

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>
Orry
  • 659
  • 6
  • 21
3

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

.center>div {
  margin: auto;
  background-color: green;
  width: 200px;
}
<div class="center">
  <div>You text</div>
</div>

JsFiddle

Lex Podgorny
  • 2,598
  • 1
  • 23
  • 40
3

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

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

    #child {
        display: inline-block;
    }
Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
2

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

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;
}
Ram
  • 3,092
  • 10
  • 40
  • 56
  • Instead of `margin-left:auto;` and `margin-right:auto;`, you might want to write `margin: 0 auto;` – CoderPi Dec 01 '15 at 08:06
1

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.

krekto
  • 1,403
  • 14
  • 18
1

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>
azakgaim
  • 309
  • 3
  • 6
0

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>
amachree tamunoemi
  • 817
  • 2
  • 16
  • 33
-3

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"
        });
    });
});
Riccardo Volpe
  • 1,471
  • 1
  • 16
  • 30
-4

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

.cenverDiv{
    position:relative;
    left:30%;
    top:0px;
}
goli55
  • 61
  • 1
  • 2