copenndthagen
copenndthagen

Reputation: 50732

Best way to center align a div with unknown width and height?

Say I have a div on my page as:

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

My CSS looks something like:

.center{
    background:red;
    position:absolute;
    left:50%;
    top:50%;
    margin-left: ?
    margin-top: ?
}

So as you can see above, the only thing that I need to know is how to set margin-left and margin-top values. If I had a known width and height of .center div (say 300px each), I would have set margin-left and margin-top values as half of that value (-150px both)

But my question is how do I set those values if width/height of .center div is unknown (or say it's dynamic)?

Can I use some kind of CSS expression OR does that have cross-browser limitations? What's the best way to do this?

Upvotes: 2

Views: 7422

Answers (5)

Matt Coughlin
Matt Coughlin

Reputation: 18906

With no explicit width, no ancestor elements to make use of, and only a single div, the only option left may be to use JavaScript or jQuery (if that's an option).

JSFiddle demo using jQuery (dynamically set the margin).

CSS

.center {
    position: absolute;
    left: 50%;
    top: 50%;
}

jQuery

var leftOffset = $('.center').width() >> 1;
var topOffset = $('.center').height() >> 1;
$('.center').css('margin', '-' + topOffset + 'px 0 0 -' + leftOffset + 'px');

Upvotes: 1

Yannick Schuchmann
Yannick Schuchmann

Reputation: 502

If your div hasn't a fixed size, unfortunately the only way is to use javascript.

For example (jsFiddle Demo):

Javascript(jQuery)

var $container = $('#centered');

var mLeft = $container.outerWidth() / 2;
var mTop = $container.outerHeight() / 2;

$container.css({
    'margin-left': -mLeft, 
    'margin-top': -mTop,
});

CSS:

html, body {
    height: 100%;
}
#centered {
    position: absolute;
    left: 50%;
    top: 50%;
    background: red;
}

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149020

To center horizontally is pretty easy. Use

width: 50%; /* or anything other than auto */
margin-left: auto;
margin-right: auto;

or alternatively:

margin: 0 auto;

To center vertically, it's a bit more difficult, and depends a lot on the other elements surrounding your div. See this article for some pointers.

Upvotes: 4

Tsimtsum
Tsimtsum

Reputation: 1021

To make div center of the page. Width property must be set.

.center{
   background:red;
   margin: 0 auto;
   width:500px;
}

Upvotes: 0

Eric Rini
Eric Rini

Reputation: 1890

Simplest version of this pattern.

 .center-block
 {     
      margin: 0 auto
 }

Upvotes: 4

Related Questions