如何垂直对齐div中的元素? [英] How can I vertically align elements in a div?

查看:27
本文介绍了如何垂直对齐div中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div 包含两个图像和一个 h1.所有这些都需要在 div 内垂直对齐,彼此相邻.

其中一张图片需要 absolute 定位在 div 内.

它需要什么 CSS 才能在所有常见浏览器上运行?

解决方案

哇,这个问题很流行.它基于对 vertical-align 属性的误解.这篇出色的文章对此进行了解释:

了解vertical-align,或如何(不)垂直居中内容",作者:Gavin Kistner.

如何在 CSS 中居中" 是一个很棒的网络工具,可以帮助您找到不同情况下必要的 CSS 居中属性.

<小时>

简而言之(并防止链接腐烂):

  • 内联元素(以及内联元素)可以通过vertical-align: middle在其上下文中垂直对齐.但是,上下文"不是整个父容器的高度,而是它们所在文本行的高度. jsfiddle例子
  • 对于块元素,垂直对齐更难,很大程度上取决于具体情况:
    • 如果内部元素可以有固定高度,则可以使其位置absolute并指定其heightmargin-toptop 位置.jsfiddle 示例
    • 如果居中元素由单行组成 并且 其父高度是固定的,您可以简单地设置容器的line-height 填充其高度.根据我的经验,这种方法非常通用.jsfiddle 示例
    • ……还有更多这样的特殊情况.

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 its height, margin-top and top 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中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆