简体   繁体   中英

Vertically center text using box-align on inline-block element

I'm trying to center text vertically in an inline-block element (and particularly in webkit browsers). Pretty much exactly what the <button> element does out of the box.

I've tried using box-align, as in this question Vertical align text in block element but I don't want to set an explicit width on the element: I want it to fit to its contents, ie I want display: inline-block type behavior.

In Firefox, -moz-box appears to behave the way I want, but in Safari and Chrome, -webkit-box makes the div want to fill its container horizontally.

[oops, can't post image as I'm a noob]

Fiddle here with examples of various settings.

Looking at webkit's inspector on an actual <button> element, it defaults to display: inline-block and yet it obeys -webkit-box-align as if it were set to display: -webkit-box. See the fiddle where I explicitly set display:inline-block and -webkit-box-align: end on a <button> to demonstrate.

It seems that by adding an extra <div> into the mix, I can get the behavior I want, but I'd really rather not do that. I'm also aware of the display: table-cell technique for vertical centering; this is not appropriate here as it has other side-effects.

So is webkit's behavior correct? How does the <button> element do what the <div> can't? Is there some under-the-hood webkit CSS property that I haven't spotted that could make the <div> behave like the <button>? Or even better, any cross-browser way of doing this?

use line-height property of css. make it equal to the height of the box containing text.

http://www.w3schools.com/cssref/pr_dim_line-height.asp

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