问题描述
我有一个包含两个图像的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.
其中一张图像需要absolute
放置在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
或如何(不)垂直居中显示内容" 加文·基斯纳(Gavin Kistner).
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 :
- 内联元素(并且仅 内联元素)可以通过
vertical-align: middle
在其上下文中垂直对齐.但是,上下文"不是整个父容器的高度,而是它们所在的文本行的高度. jsfiddle例子 - 对于块元素,垂直对齐更加困难,并且在很大程度上取决于特定情况:
- 如果内部元素可以具有固定高度,则可以将其放置在
absolute
位置,并指定其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.
这篇关于如何在div中垂直对齐元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- If the inner element can have a fixed height, you can make its position
- 如果内部元素可以具有固定高度,则可以将其放置在