19

I read that the <center> tag is deprecated, however I cannot find any real equivalent to it in CSS. text-align works for text but not other elements, and auto margins only work if you know the width of the container (so not a solution if you don't know the width in advance). So is there any real equivalent to this <center> tag?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
laurent
  • 88,262
  • 77
  • 290
  • 428

2 Answers2

31

text-align should work for other kinds of elements. Does this work?

.center { margin: auto; text-align: center; }

Edit Three Years Later :-D

margin: auto; also makes the top and bottom margins "auto". That might not be what you want. Alternatively you could have something like:

.center {
  margin-left: auto;
  margin-right: auto;
  margin-top: 3px;
  margin-bottom: 3px;
  text-align: center;
  display: flex;
  justify-content: center;
}

This particular example will center the text horizontally while hardwiring the upper and lower margins to 3 pixels.

One can also say something like margin: 3px auto 3px auto; but I prefer spelling out the directions explicitly, as I can never quite remember what the order of the parameters are if I put them all on the one margin: setting.

Justin Liu
  • 581
  • 6
  • 21
Mike Crawford
  • 2,232
  • 2
  • 18
  • 28
  • 14
    To remind myself of the order of the parameters for the "shorthand", I think of the word, **"terrible"**. Like, "Wow, this shorthand syntax is terrible." :) (TRBL: **Top Right Bottom Left**) – rinogo Jun 12 '15 at 00:03
  • 5
    goes clockwise, starting at the top. – Malachi May 12 '16 at 14:22
  • center also does something "else" that is important, it makes himself a width:100% container. That's why for some those 2 (margin: auto; text-align: center;) won't work while center tag will – Nertan Lucian May 03 '20 at 21:05
12

There is a difference:

<center>
  <span>Works</span>
</center>

<span style="margin: auto; text-align: center;"> And this is broken</span>

<div style="margin: auto; text-align: center;">But this works works</div>
Community
  • 1
  • 1
Isaksen
  • 184
  • 1
  • 4