PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 17, 2022

[FIXED] How can I use CSS to vertically center the text in an anchor, within a LI?

 November 17, 2022     css, vertical-alignment     No comments   

Issue

Variations on this question have been asked many times. Vertical centering with CSS is a challenge.

I have a particular scenario, dealing with a list displayed horizontally. The markup is like this:

  <ul id='ul1' class='c'>
    <li><a href='javascript:void(0)'>Fribble Fromme</a></li>
    <li><a href='javascript:void(0)'>Fobble</a></li>
    <li><a href='javascript:void(0)'>Foo Fickle Pickle</a></li>
  </ul>

The style is like this:

  ul.c {
    height:52px;
    text-align:center;
  }
  ul li a {
    float:left;
    text-decoration:none;
    border: 1px solid Maroon;
    padding:2px 12px;
    background:#FFEF8A;
    line-height:1em;
    width:100px;
  }
  ul li a:hover {
    background: #CCC;
  }
  ul li {
    height:52px;
    display:inline-block;
  }

The resulting list looks like this:

enter image description here

But I want all the boxes to be the same height, and I want the text to be vertically centered in each box. I can set the box-height by adding a height style for the A elements. The result looks like this:

enter image description here

...which is close to what I want, but the vertical-centering isn't happening.

I can set line-height for the text, as suggested in this post, to do the vertical centering. I can even pick different values of line-height for different A elements, if I know which of the elements will get multiple lines of text. But I don't know which ones will require multiple lines.

How can I get it to center when some of the A elements have text that wraps?


Solution

You could use display:table, etc. along with vertical-align:middle

ul.c {
    text-align:center;
    display:table;
}

ul li {   
    float:left;    
}

ul li a {
    text-decoration:none;
    border: 1px solid Maroon;
    padding:2px 12px;
    background:#FFEF8A;
    width:100px;
    height:52px;
    display:table-cell;
    vertical-align:middle;
}

ul li a:hover {
    background: #CCC;
}

Example: http://jsfiddle.net/kf52n/2/



Answered By - Jason Gennaro
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing