Vertically centering text within an inline-block

前提是你 提交于 2019-11-27 02:05:30

问题


I'm trying to create some buttons for a website using styled hyperlinks. I have managed to get the button looking how I want, bar one slight issue. I can't get the text ('Link' in the source code below) to vertically center.

Unfortunately there may be more than one line of text as demonstrated with the second button so I can't use line-height to vertically center it.

My initial solution was to use display: table-cell; rather than inline-block, and that sorts the issue in Chrome, Firefox and Safari but not in Internet Explorer so I'm thinking I need to stick to inline-block.

How would I go about vertically centering the link text within the 57px x 100px inline-block, and have it cater to multiple lines of text? Thanks in advance.

CSS:

.button {
    background-image:url(/images/categorybutton-off.gif);
    color:#000;
    display:inline-block;
    height:57px;
    width:100px;
    font-family:Verdana, Geneva, sans-serif;
    font-size:10px;
    font-weight:bold;
    text-align:center;
    text-decoration:none;
    vertical-align:middle;
}
.button:hover {
    background-image:url(/images/categorybutton-on.gif);
}
.button:before {
    content:"Click Here For\A";
    font-style:italic;
    font-weight:normal !important;
    white-space:pre;
}

HTML:

<a href="/" class="button">Link</a>
<a href="/" class="button">Link<br />More Details</a>

回答1:


Wrap your text with a span (Centered), and write another empty span just before it(Centerer) like this.

HTML:

<a href="..." class="button">
  <span class="Centerer"></span>
  <span class='Centered'>Link</span>
</a>

CSS

.Centered
{
    vertical-align: middle;
    display: inline-block;
}

.Centerer
{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

Take a look here: http://jsfiddle.net/xVnQ6/




回答2:


Many thanks @avrahamcool, works like a charm!

I have a little upgrade. You can replace redundant .Centerer span with css

.button:before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

See demo here: http://jsfiddle.net/modernweb/bXD2V/

NOTE: This will not work with text in "content" attribute.



来源:https://stackoverflow.com/questions/18485378/vertically-centering-text-within-an-inline-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!