如何在div中垂直对齐元素?
我有一个带有两个图像的 div
和一个 h1
.所有这些元素都需要在div内垂直对齐,并且彼此相邻.
I have a div
with two images and an h1
. All of them need to be vertically aligned within the div, next to each other.
其中一张图片需要在 div
内绝对
放置.
One of the images needs to be absolute
positioned within the div
.
要在所有常见的浏览器上运行,需要什么CSS?
What is the CSS needed for this to work on all common browsers?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
哇,这个问题很普遍.它基于对 vertical-align
属性的误解.这篇出色的文章对此进行了解释:
Wow, this problem is popular. It's based on a misunderstanding in the vertical-align
property. This excellent article explains it:
了解 vertical-align
或如何(不)垂直居中放置内容" .
Understanding vertical-align
, or "How (Not) To Vertically Center Content" by Gavin Kistner.
如何在CSS中居中" 是一个很好的网络工具,可帮助您找到不同情况下必需的CSS居中属性.
"How to center in CSS" is a great web tool which helps to find the necessary CSS centering attributes for different situations.
简而言之(并防止链接腐烂):
In a nutshell (and to prevent link rot):
- 内联元素(和仅内联元素)可以通过
vertical-align:middle
在其上下文中垂直对齐.但是,上下文"不是整个父容器的高度,而是它们所在的文本行的高度. jsfiddle例子 - 对于块元素,垂直对齐更加困难,并且在很大程度上取决于特定情况:
- 如果内部元素可以具有固定高度,则可以将其位置设置为
绝对
,并指定其height
,margin-top
和top
位置. jsfiddle示例 - 如果居中元素由单行组成 和 其父级高度固定,则只需设置容器的
line-height
以填充其高度.根据我的经验,这种方法用途广泛. jsfiddle示例 - …还有更多这样的特殊情况.
-
Inline elements (and only inline elements) can be vertically aligned in their context via
vertical-align: middle
. However, the "context" isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example - For block elements, vertical alignment is harder and strongly depends on the specific situation:
- If the inner element can have a fixed height, you can make its position
absolute
and specify itsheight
,margin-top
andtop
position. jsfiddle example - If the centered element consists of a single line and its parent height is fixed you can simply set the container’s
line-height
to fill its height. This method is quite versatile in my experience. jsfiddle example - … there are more such special cases.
- If the inner element can have a fixed height, you can make its position
- 如果内部元素可以具有固定高度,则可以将其位置设置为