Is it possible to horizontally center an inline element without extra markup or styling parent containers?

17,756

Solution 1

Try this - DEMO

a {
    display: table;
    margin: auto;
}

Solution 2

I personally try not to change an elements display type if at all possible, especially to something like 'table' for accessibility reasons.

The normal margin: 0 auto; trick does not work here unfortunately.

Hope this helps!

a {
  display: inline-block;
  left: 50%;
  transform: translateX(-50%);
  position: relative;
}
<a href="#">Center Me</a>
Share:
17,756
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin about 2 years

    The question is basically already stated in the title, but to clarify: I'm trying to horizontally center an anchor <a> in a main content area.

    I would like to do this without:

    • Using fixed widths
    • Adding extra markup (an extra parent div for example)
    • Styling the parent container (so setting the parent to text-align:center for example)
    • Setting the <a> as a full width block (I would like to keep the clickable area a big as the link itself)

    So basically I would like to do this just by styling the anchor itself in css, in a dynamic (shrinkwrap) way. I've been trying, but haven't found a way yet, does anyone know how to do this?

  • Stuart Nelson
    Stuart Nelson almost 6 years
    While your answer is correct in terms of how to centre an element, the question asks how to centre an inline-block element. Making it a block level element would defeat the object.
  • Michael Iyke
    Michael Iyke almost 5 years
    This question was asked years ago and I stumbled on it today. You just saved my day thanks. What I wanted to achieve was center an element without giving it a particular width for responsiveness and this answer was the killer!
  • Nick Asher
    Nick Asher about 3 years
    you saved so much time. Thank you