How can I vertically align elements in a div?(如何垂直对齐 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.
One of the images needs to be absolute
positioned within the div
.
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>
Wow, this problem is popular. It's based on a misunderstanding in the vertical-align
property. This excellent article explains it:
Understanding vertical-align
, or "How (Not) To Vertically Center Content" by Gavin Kistner.
"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):
- 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
这篇关于如何垂直对齐 div 中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何垂直对齐 div 中的元素?
基础教程推荐
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06