div中元素的垂直对齐(How to Vertical align elements in a div?)

系统教程 行业动态 更新时间:2024-06-14 17:02:18
div中元素的垂直对齐(How to Vertical align elements in a div?)

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

其中一个图像需要在div中absolute定位。

在所有常用浏览器上工作的CSS需要什么?

<div id="header"> <img src=".." ></img> <h1>testing...</h1> <img src="..."></img> </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>

最满意答案

哇,这个问题很受欢迎。 这是基于vertical-align属性的误解。 这篇优秀的文章解释说:

了解vertical-align ,或者“如何(不)垂直居中的内容”由Gavin Kistner。

“CSS如何中心”是一个很棒的网络工具,可帮助您找到不同情况下必需的CSS中心属性。


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

内联元素 (和只有内联元素)可以通过vertical-align: middle在其上下文中vertical-align: middle 。 然而,“上下文”不是整个父容器高度,它们是它们所在的文本行的高度。jsfiddle示例 对于块元素,垂直对齐更难,强烈依赖于具体情况: 如果内部元素可以具有固定高度 ,则可以将其位置设置为absolute并指定其height , margin-top和top位置。 jsfiddle示例 如果居中的元素由一条线组成, 并且 其父高度是固定的,您可以简单地设置容器的line-height来填充其高度。 这种方法在我的经验中是非常通用的。 jsfiddle示例 ...还有更多这样的特殊情况。

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.

更多推荐

本文发布于:2023-04-21 18:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d13ae8443167191c525b1e2a218edecc.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   div   Vertical   elements   align

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!