Question

I am trying to center an anchor horizontally AND vertically inside a list.

#menu li a {
    display: inline-block;
    width: 100%;
    height: 40px;
    padding: 12px 0 12px 0;
    text-decoration: none;
    color: #AAAAAA;
    font-size: 40px;
    text-shadow:
        -2px -2px 0 #000,    
        2px -2px 0 #000,
        -2px 2px 0 #000,
        2px 2px 0 #000;
}

http://jsfiddle.net/9FEDC/2/

All I want is an anchor that:

  • is horizontally and vertically centered
  • stretches accross the entire parent

EDIT: text-align is working fine but not even vertical-align: middle is working.

EDIT 2: As suggested, I'm now using a line-height equal to the anchor's height. This does indeed get the anchor closer to its vertical center, but for some reason it is still a few pixels off its true vertical center. Here's an updated fiddle... http://jsfiddle.net/zp5GM/1/

EDIT 3: just out of curiosity I defined a 1px solid border for the anchor element and saw that the text INSIDE the anchor itself is not centered vertically. So things like vertical-align or even position changes to the anchor do not affect anything in this regard. Can somebody please explain this weird behavior?

Was it helpful?

Solution

As has been mentioned, your markup is invalid. Once that is fixed, you can center the anchor tag by doing something similar to this:

Set the width and text alignment to the anchor's parent instead of the anchor itself.

li {
  text-align: center;
  width: 100%;
}

To vertically align and element, you can take different approaches. The easiest is probably to give the element the same height and line-height. That way it will vertically center the text.

<div class="parent-element">
  <div class="child-element">
    <p>This is some text.</p>
  </div>
</div>

.parent-element {
  width: 100%;
}

.child-element {
  height: 100px;
  line-height: 100px;
}

You can also position it 50% from the top and then subtract half the height of the child element.

<div class="parent-element">
  <div class="child-element">
    <p>This is some text.</p>
  </div>
</div>

.parent-element { position: relative; }
.child-element {
  height: 100px;
  margin-top: -50px;
  position: absolute;
  top: 50%;
}

OTHER TIPS

text-align:center;

That should do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top