silow
silow

Reputation: 4306

css trick for centering horizontal and vertical

My .cent class is for <li> elements. I want to center the text of the <li> both horizontally and vertically. text-align:center; takes care of horizontal centering, but the vertical centering isn't working. What's the CSS trick for this?

.cent{
  height:20px;
  width:20px;
  text-align:center;
  vertical-align: middle;
}

Upvotes: 5

Views: 1603

Answers (3)

Thilak
Thilak

Reputation: 590

Try to set the style for li tag, margin and padding tags are will help you

Like,

# set default
li 
  {
  margin: 0;
  padding: 0;
  }

after write the style for your class cent, it will be affect the li tag properly.

Upvotes: 0

tomsseisums
tomsseisums

Reputation: 13377

Use line-height property.

Set it equal to height of element, and text will be vertically centered.

.cent{
  height: 20px;
  width: 20px;
  text-align: center;
  /*vertical-align: middle;*/
  line-height: 20px;
}

Upvotes: 7

alex
alex

Reputation: 490607

What is its parent?

.parent {
   position: relative;   
}

.cent {
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: -10px;
   margin-top: -10px;
}

Or if you want vertical-align: middle to work, set display: table-cell.

Upvotes: 1

Related Questions