8
votes

Does anybody know how to center align a DIV that has the display set to inline-block?

I cannot set the display to block because I have a background image that needs to be repeated, and it needs to expand based on the content. It sits inside of a parent div, in which is larger when it comes to width.

So all in all. Does anyone have a fix to center align a div with the display set to inline-block?

And no, text-align: center; does not work, nor does margin: 0 auto;

jsFiddle: http://jsfiddle.net/HkvzM/

Thank you!

5
"I cannot set the display to block because I have a background image that needs to be repeated, and it needs to expand based on the content." Both of these are possible for block elements. Show us an example of what you're trying to do.ceejayoz
@ceejayoz: I updated my question with the link to the jsFiddle. Thank you!Aaron Brewer

5 Answers

17
votes

Try using this:

margin: 0 auto;

Or text-align: center; on the parent <div>...

2
votes

Hi you can give parent text-align center not child as like this

Css

div{
    text-align: center;

}

.dl{
    color: #fff;
    margin: 0 auto;
    background: #000;
    text-transform: uppercase;
    font-size: 14px;
    font-weight: bold;  
    line-height:35px;  
    display:inline-block;    
}

HTML

<div>
<a class="dl">DOWNLOAD NOW DOWNLOAD NOW DOWNLOAD NOW</a>    
</div>

Live demo here http://jsfiddle.net/rohitazad/HkvzM/15/

1
votes

You can not center an element with

display:inline

You might have to find a work around by using jQuery or JavaScript. You can do some approximate centering with CSS which will work if the text does not change that much in length. Something like this Demo

<div id="out">
    <a class="dl">DOWNLOAD NOW DOWNLOAD NOW DOWNLOAD NOW</a>
</div>​​​

#out{
 padding:0 50px;   
}
0
votes

text-align:center on the parent div , will simply do the trick.
source : CSS center display inline block?

0
votes

What I've gotten from all of these (many, multitude, gobs of) answers is that you cannot center a block with an inline style call. It must be a defined class. Here's the canary:

<div
  style="font-size: 14pt; text-align: center; font-family: latoweb; font-weight: 400; display: inline-block; margin: 0 auto; width: 80%; height: auto;"
>
  <a
    id="media_comment_m-4JGUVJ6vm4uhihPBSiXrZGRG2Fm1a8To"
    data-media_comment_type="video"
    class="instructure_inline_media_comment video_comment mce-item-anchor"
    data-alt=""
  >
  </a>
  5 Quick Steps to <i>Photo Story 3</i>
</div>

Trying to center a video frame inside of Canvas LMS. Must pass their whitelist test.