How to center a div container

How can I horizontally center a <div> within another <div> using CSS (if it's even possible) when the outer <div> has width: 100%?

For example:

<div id="outer" style="width: 100%">     <div id="inner">Foo foo</div> </div> 

Replay

You can apply this CSS to the inner div:

#inner {
    width: 50%;
    /* Set the margin-left and margin-right automatically set */
    margin: 0 auto;
}

Of course, you don't have to set the width to 50%. Any width less than the containing div will work. The margin: 0 auto is what does the actual centering.

If you are targeting IE8+, it might be better to have this instead:

#inner {
    display: table;
    margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width.

If you don't want to set a fixed width on the inner div you could do something like this:

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

#inner {
  display: inline-block;
}

That makes the inner div into an inline element that can be centered with text-align.

Suppose that your div is 200px wide:

.centered {
  position: absolute;
  left: 50%;
  margin-left: -100px;
}

Best approaches with CSS 3

box model:

#outer{
    width:100%;

    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;

    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;

    /* W3C */
    display:box;
    box-pack:center;
    box-align:center;
}
#inner{
    width:50%;
}

According to your usability you may also use the box-orient, box-flex, box-direction properties.

flex :

#outer {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

Here is a playground for centering elements with box model.

Read more about centering the child elements

And this explains why box model is best approach.

  • Why is the W3C box model considered better?

I've created this example to show how to vertically and horizontally align.

Code is basically this:

#outer {
  position: relative;
}

and...

#inner {
  margin: auto;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

and it will stay in the center even when you re-size your screen

Hope this helps

If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.

You can use:

#element {
    display: table;
    margin: 0 auto;
}

Some posters have mentioned the css3 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 css3 using the Flexible Box Layout Module

So if you have simple markup like:

<div class="box">
  <div class="item1">A</div>
  <div class="item2">B</div>
  <div class="item3">C</div>
</div>

...and you want to center your items within the box, here's what you need on the parent element (.box):

.box {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

Here's a LIVE DEMO to play with - [which also takes into consideration browser specific properties.]

NB: This now works in Firefox 22, but for earlier version of FF - you need to enable the flexbox runtime flag like this

This post shows how to get maximum browser support for flexbox and explains some of the peculiar browser-specific properties needed in ie10)

A good place to start when trying to get the syntax right for all browsers is here.

It cannot be centered if you don't give it a width, otherwise it will take, by default the whole horizontal space.

CSS3's box-align property

#outer {
    width:100%;
    height:100%;
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
}

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

I recently had to center a "hidden" div (ie, display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery to display the hidden div & then update the CSS 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 neccessary to display.)

NOTE: I'm sharing this code because Google brought me to this Stack Overflow solution & everything would have worked except that hidden elements don't have any width & can't be resized/centered until after they are displayed.

<div id="inner" style="display:none;">
    <form action="">
    <table id="innerTable">
        <tr><td>Name:</td><td><input type="text"></td></tr>
        <tr><td>Email:</td><td><input type="text"></td></tr>
        <tr><td>Email:</td><td><input type="submit"></td></tr>
    </table>
    </form>
</div>

<script language="JavaScript" type="text/javascript">
$(function(){
    $('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
</script>

The way I usually do it is with absolute positioning:

#inner{
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
}

The outer div doesn't need any extra propertites for this to work.

Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support then the flexbox-solution, and you're not using display: table; which could break other things.

/* This parent can be any width and height */
.outer {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.outer:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */
.inner {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

I realize I'm pretty late to the game, but this is a very popular question, and I recently found an approach I haven't seen mentioned anywhere here, so I figured I'd document it.

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

EDIT: both elements must be the same width to function correctly.

HTML

<div id="outerDiv">
    <div id="innerDiv">Inner Content</div>
</div>

CSS

#outerDiv
{
    width:500px;
}

#innerDiv
{
    width:200px;
    margin:0 auto;
}

Another solution for this without having to set a width for one of the elements is using the CSS3 transform attribute.

#outer {
  position: relative;
}

#inner {
  position: absolute;
  left: 50%;

  transform: translateX(-50%);
}

The trick ist, that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.

Here's a Fiddle showing horizontal and vertical alignment.

More information on Mozilla Developer Network.

Centering a div of unknown height and width

Horizontally and vertically. Works with reasonably modern browsers (FF, Safari/Webkit, Chrome, IE10, Opera, etc.)

HTML:

<div class="content">This works with any content</div>

CSS:

.content {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Tinker with it further on Codepen or on JSBin

For Firefox & Chrome:

<div style="width:100%;">
    <div style="width: 50%; margin: 0px auto;">
    </div>
</div>

For IE, Firefox & Chrome:

<div style="width:100%; text-align:center;">
    <div style="width: 50%; margin: 0px auto; text-align:left;">
    </div>
</div>

The text-align: property is optional.

You can do something like this

#container {
   display: table;
   width: <width of your container>;
   height: <height of your container>;
}

#inner {
   width: <width of your center div>;
   display: table-cell;
   margin: 0 auto;
   text-align: center;
   vertical-align: middle;
}

This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;

Well, I managed to find a solution that maybe will fit all situations, but uses javascript:

Here's the structure:

<div class="container">
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
</div>

And here's the javascript snippet:

$(document).ready(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

If you want to use it in a responsive approach, you can add the following:

$(window).resize(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

For example see this link.

<div id="outer" style="width:100%;">
    <div id="inner">Foo foo</div>
</div>

And your css looks like this

div#outer {
    height: 120px;
    background-color: red;
}

div#inner {
    width: 50%;
    height: 100%;
    background-color: green;
    margin: 0 auto;
    text-align:center; /* For Text alignment to center horizentaly. */
    line-height: 120px; /* For Text alignment to center verticaly. */
}

If you have a lot of children under a parent, so your css must be like this example on fiddle.

Html look likes this

<div id="outer" style="width:100%;">
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> Foo Text </div>
</div>

Then see this example on fiddle.

Here is what you want in the shortest way.

JSFIDDLE

#outer {
    margin - top: 100 px;
    height: 500 px; /* you can set whatever you want */
    border: 1 px solid# ccc;
}

#inner {
    border: 1 px solid# f00;
    position: relative;
    top: 50 % ;
    transform: translateY(-50 % );
}

Try playing around with

margin: 0 auto;

If you want to center your text too, try using:

text-align: center;

one option is existed that i found every body say use

margin: auto 0;

but there is another option set this property for parent div , it is anytime work perfect

text-align:center;

and see , child go center

and finally css for you

#outer{
     text-align:center;
     display:block;/* or inline-block - base on your need*/
}

#inner
{
     position:relative;
     margin:0 auto; /* it is good to be */
}

The easiest way:

<div id="outer">
    <div id="inner"></div>
</div>

<style>
    #outer {
        width:100%;
        text-align:center;
    }
    #inner {
        margin:auto;
        width:200px;
    }
</style>

Fiddle: http://jsfiddle.net/joan16v/fnaqakdn/

If width of the content is unknown, you can use the following method that requires one extra element. Suppose we have these two elements:

  • outer (100% wide, suppose it is 1000px wide)
  • inner (no width defined, suppose it is 300px wide)

Proceed as follows:

  1. Wrap inner inside center-helper
  2. Float center-helper; it becomes same size as inner (this makes it 300px wide)
  3. Push center-helper 50% right relative to its parent (this places its left at 500px wrt. outer)
  4. Pull inner 50% left relative to its parent (this places its left at -150px wrt. center-helper which means its left is at 500 - 150 = 350px wrt. outer)
  5. Set overflow on outer to hidden

Here is the CSS:

.outer {
    overflow: hidden;
}
.center-helper {
    float: left;
    position: relative;
    left: 50%;
}
.inner {
    float: left;
    position: relative;
    left: -50%;
}

And here is the demo

#inner {
    width: 50%;
    margin: 0 auto;
}

If Anyone would like a Jquery for center align these divs

$(window).bind("load", function() {
        var wwidth = $("#outer").width();
        var width = $('#inner').width();
        $('#inner').attr("style","padding-left: "+wwidth/2+"px; margin-left: -"+width/2+"px;");
    });

How about the below CSS for #inner div:

#inner {
  width: 50%;
  margin-left: 25%;
}

I mostly use this CSS to center divs.

Nice thing I recently found, mixing the use of line-height+vertical-align and the 50% left trick, you can center a dynamically sized box inside another dynamically sized box, on both the horizontal and vertical using pure CSS.

Note you must use spans (and inline-block), tested in modern browsers + IE8. HTML:

  <h1>Center dynamic box using only css test</h1>
    <div class="container">
        <div class="center">
            <div class="center-container">
                <span class="dyn-box">
                    <div class="dyn-head">This is a head</div>
                    <div class="dyn-body">
                        This is a body<br />
                        Content<br />
                        Content<br />
                        Content<br />
                        Content<br />
                    </div>
                </span>
            </div>
        </div>
    </div>

CSS:

        .container
        {
            position:absolute;
            left:0;right:0;top:0;bottom:0;
            overflow:hidden;
        }
        .center
        {
            position:absolute;
            left:50%; top:50%;
        }
        .center-container
        {
            position:absolute;
            left:-2500px;top:-2500px;
            width:5000px;height:5000px;
            line-height:5000px;
            text-align:center;
            overflow: hidden;
        }
        .dyn-box
        {
            display: inline-block;
            vertical-align: middle;
            line-height: 100%;

            /* Purely asthetic below this point */
            background: #808080;
            padding: 13px;
            border-radius: 11px;
            font-family: arial;
        }
        .dyn-head
        {
            background:red;
            color:white;
            min-width: 300px;
            padding: 20px;
            font-size: 23px;
        }
        .dyn-body
        {
            padding: 10px;
            background:white;
            color:red;
        }

See example here.

Category: html Time: 2008-09-22 Views: 2

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.170 (s). 12 q(s)