Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

html - 如何在div中垂直对齐元素?(How to Vertical align elements in a div?)

I have a div with two images and an h1 .

(我有一个带两个图像的div和一个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.

(其中一张图片必须absolute位于div内。)

What is the CSS needed for this to work on all common browsers?

(要在所有常见的浏览器上运行,需要什么CSS?)

<div id="header">
    <img src=".." ></img>
    <h1>testing...</h1>
    <img src="..."></img>
</div>
  ask by Abdu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Wow, this problem is popular.

(哇,这个问题很流行。)

It's based on a misunderstanding in the vertical-align property.

(它基于对vertical-align属性的误解。)

This excellent article explains it:

(这篇出色的文章对此进行了解释:)

Understanding vertical-align , or "How (Not) To Vertically Center Content" by Gavin Kistner.

(加文·基斯纳(Gavin Kistner )了解“ vertical-align ”或“如何(不)使内容垂直居中” 。)

“How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations.

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


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 .

    (内联元素 (并且内联元素)可以通过vertical-align: middle在其上下文中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

    (但是,“上下文”不是整个父容器的高度,而是它们所在的文本行的高度。jsfiddle示例)

  • 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.

      (如果内部元素可以具有固定的height ,则可以使其absolute位置并指定其heightmargin-toptop位置。)

      jsfiddle example

      (jsfiddle示例)

    • 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.

      (如果居中元素由单条线组成, 并且 其父级高度是固定的 ,则可以简单地设置容器的line-height来填充其高度。)

      This method is quite versatile in my experience.

      (根据我的经验,此方法用途广泛。)

      jsfiddle example

      (jsfiddle示例)

    • … there are more such special cases.

      (……还有更多这样的特殊情况。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...