If I give header an auto margin and a width, it's horizontally centered. What's the least horrible way to ensure that it's vertically centered, as well?
如果我给标头一个自动边距和宽度,它是水平居中。要保证它是垂直居中的,最不可怕的方法是什么?
I am aware of the following articles which provide some discussion of the topic:
Since this question was tagged CSS3, here's a "least horrible" solution using CSS3's "flexbox". Unfortunately only recent versions of Safari, Chrome and Firefox support it.
note that I set 100% height on the html node, which really isnt proper css as far as I know, it should be on the body and header should be in a encapsulating div wich has display: table http://jsfiddle.net/bgYPR/2/
Unfortunately, there's still nothing elegant for vertical alignment, only hacks.
不幸的是,对于垂直对齐仍然没有什么优雅可言,只有一些技巧。
#4
2
I don't know if there's a best way, but there are a number of different ways (depending on your situation), and many are thoroughly discussed in this article.
我不知道是否有最好的方法,但是有许多不同的方法(取决于您的情况),本文将详细讨论其中的许多方法。
#5
1
Usually when I need vertical centering I use a pair of inline-block elements. You have one element that is the full height of the container, and a second element that is only the height of the content to be centered. Both are display:inline-block;vertical-align:middle.
I like to use b tags for this, because they have no semantic significance and are tiny:
我喜欢使用b标签,因为它们没有语义意义,而且很小:
This is my centered content It makes me happy!
Mind you, this specific code example wont work in IE7 because of the lack of inline-block and sibling selectors (+), but the same technique can be done using more complex code that IE7 will handle.
I would generally not verticially center, but specify a small top margin like 20px. We don't always know enough about the end user's equipment to make an assumption about what is convenient or usable for the platform they are viewing the site on.