1

I am trying to horizontally-align an element (<div id='content'>) within a div (<div id='container'>)

content may be narrower or wider than the container's width. I need it to be always centered.

How do you do that using CSS3?

See the jsFiddle: http://jsfiddle.net/ja26Z/

Aximili
  • 28,626
  • 56
  • 157
  • 216
  • Look at [this question](http://stackoverflow.com/questions/114543/how-to-center-a-div-in-a-div-horizontally?rq=1) and see if it helps. :) – icedwater Jul 05 '13 at 01:37

3 Answers3

2

you basically had it, just a spelling error. Update your css to American spelling, text-align:center;

updated fiddle http://jsfiddle.net/ja26Z/3/

lukeocom
  • 3,243
  • 3
  • 18
  • 30
  • Ah thanks I wonder why it didn't work. But it doesn't solve the problem where the content is wider than the container. – Aximili Jul 05 '13 at 01:58
  • Yeah that's a hard problem to solve with just CSS. Id be interested in seeing the solution if you find one. Although it would likely be quicker to just write a script... – lukeocom Jul 05 '13 at 02:12
2

Or you can place the #content div in another div:

http://jsfiddle.net/ja26Z/6/

Mathijs
  • 73
  • 3
  • I just realised my container width can also change. But this is the best answer for the question. – Aximili Jul 05 '13 at 02:04
1

How about this: http://jsfiddle.net/wVGrN/3/

The #content will always be aligned to the center of #container even when it's wider than the container.

HTML

<div id='container'>
    <div id='content'></div>
</div>

CSS

#container { 
    position: relative; top: 10px; left: 100px; width: 100px; height: 100px; border: 3px solid #666; 
    text-align: center; 
}
#content { 
    display: inline-block; 
    height: 94px; 
    border: 3px solid #99ccff; 
    margin: 0 auto;
    position: absolute;
    left: 50%;
}

Testing script

/* This script here is only to demonstrate content with various width, it won't be used in production */
$(function(){
    ResizeContent();
});
function ResizeContent(){
    var width = Math.floor((Math.random()*150)+20);
    var marginLeft = -width / 2;
    var borderWidth = 3;
    $('#content').width(width);
    $('#content').css('margin-left', marginLeft-borderWidth);
    setTimeout(ResizeContent, 1000);
}
Stanley
  • 5,057
  • 4
  • 34
  • 44