Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center a link within a div

Tags:

html

css

I have an unordered list...

<ul class="hide">
  <li class="home">
    <div class="link">
      <a href="/">Home</a>
    </div>
  </li>
  <li class="about">
    <div class="link">
      <a href="/about">About Our Community</a>
    </div>
  </li>
  <li class="contact">
    <div class="link">
      <a href="/contact">Contact Us</a>
    </div>
  </li>
</ul>

My CSS looks like this....

#sitenav ul li .link a {
  color: #555;
  text-decoration: none;
  float: left;
  padding-right: 3px;
  margin-top: auto;
  margin-bottom: auto;
}

But the margins do not center the link vertically

Any ideas?

like image 678
Jackie Avatar asked Jun 13 '12 16:06

Jackie


2 Answers

This solution could work for you: http://jsfiddle.net/WLQAS/8/

margin-top: auto; and margin-bottom: auto; don't work to align vertically the objects.

Updated CSS

li {
  color: #555;
  text-decoration: none;
  float: left;
  padding-right: 3px;    
}

.link {
    vertical-align: middle;
    display: table-cell;
    height: 50px;
}
like image 164
Luis Avatar answered Sep 27 '22 21:09

Luis


Here's a cross browser compatible solution for vertical aligning an a-element with an unknown height within a div:

Works with link texts with and without line-breaks.

CSS

* { margin: 0; padding: 0 }

ul {}
ul li {
    display: table;
    height: 75px;
    #position: relative; /* ie hack */
    overflow: hidden;
    border: 1px solid red;
}

ul li div {
    #position: absolute; /* ie hack */
    #top: 50%; /* ie hack */
    display: table-cell;
    vertical-align: middle;
}

ul li div a {
    #position: relative; /* ie hack */
    #top: -50%; /* ie hack */
    border: 1px solid green
}

It's not recommended to use CSS hacks here, use conditional comments instead.

Live demo: http://jsfiddle.net/ahdzg/1/
More infos about this trick: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Hope this helps. Otherwise feel free to ask.

like image 42
doptrois Avatar answered Sep 27 '22 23:09

doptrois