John Ohara John Ohara - 6 months ago 11
CSS Question

CSS verically align text in <a> anchor when display type block

I'm not too sure this can be done without pseudo elements - but what do I know.

I have a tab element which is an

<LI>
.

Inside each LI there is an
<A>
.

I want to achieve 2 things:


  1. Make the A element fill the space of its parent LI. The height is
    known but the width is variable.

  2. Centre the text vertically,



Obviously this is easily done with 1 liners, simply add
display:block
and
line-height
to the anchor.

However, I need to allow for line wraps too.

So, to recap: fill the available space in the parent and vertically align text within its own block.

I can use flexbox or whatever, but at the moment, I can do one or the other not both.

Answer

I'm using flex-box to wrap the items, giving the li elements a height of 50 px, and then the a tag a line-height of 50px.

  • Because of the line-height, the text is vertically centered.
  • Because of flex-box, the items wrap multiline.

ul {
    width: 200px;
    height: 200px;
    border: 1px solid #c3c3c3;
  list-style:none;
  margin:0;
  padding:0;
    display: -webkit-flex; /* Safari */
    -webkit-flex-wrap: wrap; /* Safari 6.1+ */
    display: flex;
    flex-wrap: wrap;
}

ul li {
    width: 50px;
    height: 50px;
    position:relative;
    text-align:center;
}

ul li a {
  height:100%;
  display:block;
  line-height:50px;
}
ul li a:hover {
  background-color:#333;
  color:white;
}
<ul>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
</ul>

Comments