简体   繁体   中英

Vertically align text with css

What is the best way to vertically center the text in my blue box?

markup:

<div class="btn-blue">
  <span class="icon"></span>
  Some awesome text here
</div>

and the styles:

.btn-blue {
  background-color: #446598;
  color: #fff;
  display: inline-block;
  padding: 0 20px 0 0;
  line-height: 0;
}

.btn-blue .icon {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-color: #00356b;
  margin-right: 10px;
}

Here is the fiddle http://jsfiddle.net/fSa6r/

Thanks.

Add line-height: 50px; to the .btn-blue class and

vertical-align: middle; to the icon class

FIDDLE

When only one line of text is needed, I find that setting line-height to the height of the box is the easiest way to vertically center text.

There are lots of ways to vertically align text, which you can check out here: http://www.vanseodesign.com/css/vertical-centering/

My personal favourite is using CSS tables (not html tables):

html:

<div id="parent">
  <div id="child">Content here</div>
</div>

css:

#parent {display: table;}

#child {
  display: table-cell;
  vertical-align: middle;
}

This is another method to show a link as a button with icon. You could to improve this code using an sprite instead two separated images:

a.mybutton { 
    padding: 3px 0px 3px 30px; 
    color: #c00; 
}

a.mybutton:link, 
a.mybutton:visited, 
a.mybutton:active { 
    background: #fff url("https://dl.dropboxusercontent.com/u/59816767/assets/map-pin_off.png") left center no-repeat; 
}
a.mybutton:hover { background: #fff url("https://dl.dropboxusercontent.com/u/59816767/assets/map-pin_on.png") left center no-repeat; }

Here is the: fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM