Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

css - Vertical align middle on an inline-block anchor tag

I have a need for my links and buttons to look the same, but I've been unable to vertically align the text within an "a" tag in the same manner as the "button" tag. It is important to note that the tags need to be able to handle multiple lines of text (so line-height will not work).

a,button {
  display: inline-block;
  -moz-box-sizing: border-box;
  width: 150px;
  height: 150px;
  vertical-align: middle;
  border: 1px solid #000;
  text-align: center;
}

See the jsfiddle below:

http://jsfiddle.net/bZsaw/3/

As you can see, I can get it to work with a combination of a span tag inside and setting "display:table" to the "a" and setting "display:table-cell" and "vertical-align:middle" to the span, but that doesn't work in IE7.

a,button {
    width: 150px;
    height: 150px;
    border: 1px solid #000;
    text-align: center;
}

a {
    display: table;
    -moz-box-sizing: border-box;
}

a span, button span {
    vertical-align: middle;
    text-align: center;
}

a span {
    display: table-cell; 
}

Looking for a simple CSS only solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only reliable way to I've found align text vertically and allow wrapping of the text if it gets too long is with a 2 container approach.

The outer container should have a line height of at least double that specified for the inner container. In your case, that means the following:

a {
    width: 150px;
    height: 150px;
    border: 1px solid #000;
    text-align: center;
    line-height: 150px;
    display: block;
}

a span {
    display:inline;
    display:inline-table;
    display:inline-block;
    vertical-align:middle;
    line-height: 20px;
    *margin-top: expression(this.offsetHeight < this.parentNode.offsetHeight ? parseInt((this.parentNode.offsetHeight - this.offsetHeight) / 2) + "px" : "0");
}

Add float left on the a tag if you want everything inline. Here's the updated example with long text in the A tag too.. http://jsfiddle.net/bZsaw/13/

You can set the line height on the span to whatever you like and if it is less than half of the line height of the parent, it will center AND allow text wrapping if your text exceeds the parent container width. This works on all modern browsers as far as I know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...