Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS alternative to center

Tags:

css

center

People frown upon the center tag, but for me it always works just the way I want it. Nevertheless, center is deprecated so I'll make an effort.

Now I see many people suggest the cryptic CSS margin: 0 auto; but I can't even get it to work (see fiddle here). Other people will go modify position or display, but that always breaks something else.

How can I center a span using css so that it behaves exactly like the center tag?

<div class="container">
  <span class='btn btn-primary'>Click me!</span>
</div>
like image 808
Randomblue Avatar asked Jan 11 '13 21:01

Randomblue


1 Answers

Span is an inline element, and the margin: 0 auto for centering only works on non-inline elements that have a width that is less than 100%.

One option is to set an alignment on the container, though this probably isn't what you want for this situation:

div.container { text-align: center }

http://jsfiddle.net/MgcDU/1270/

The other option is to change the display property of the span:

/* needs some extra specificity here to avoid the display being overwritten */
span.btn.btn-primary { 
  display: table;
  margin: 0 auto;
}

Using display: table eliminates the need to hard code a specific width. It will shrink or grow as appropriate for its content.

http://jsfiddle.net/MgcDU/1271/

like image 157
cimmanon Avatar answered Nov 02 '22 06:11

cimmanon