center align a div with inline

aligning a div that has width is very simple just setting left and right margin to auto will do the trick:

<div style="margin:0px auto;"> 

but in most cases as the content is dynamic, I can't set a width do the div, using the inline-block has the desired result for div's width but the center aligning doesn't work. anybody have any Idea how to center a div that its width is defined by its content width?

by the way, I want to know if it is possible to do such thing with css, not with jQuery or javascript.


Give parent element text-align: center

For more info on text-align go through this link


<div style="text-align: center;">
    <div style="display: inline-block; background: yellow">Hello World</div>
</div>
  • 检查jsFiddle演示。

  • You can shrink wrap the contents with the varying width. You need two containing elements to do this, like so:

    .outer-wrapper {
       float: right;
       position: relative;
       left: -50%;
    }
    
    .inner-wrapper {
       position: relative;
       left: 50%;
    }
    

    http://jsfiddle.net/ExplosionPIlls/te4es/

    链接地址: http://www.djcxy.com/p/75672.html

    上一篇: 对齐Flex项目?

    下一篇: 中心对齐div与内联