垂直对齐属性如何工作? [英] How does the vertical-align property work?

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

问题描述

我不知道 vertical-align 何时会起作用,也不会起作用。

I do not understand when vertical-align will and won't work.

每次运行放入 vertical-align 的用例中,似乎很难解决。我知道它必须应用于内联元素。我已经读过我必须为通常不存在的元素指定 line-height 。我已经读到 height 属性必须具有静态(非自动/非%)值。我已经读到,如果某些(现代)浏览器所使用的元素自然不是内联元素,则它们不能正确处理 vertical-align 。我不清楚 vertical-align 应该在包含元素(例如 text-align )还是在元素I想要垂直对齐。

Every time I run into a use case for vertical-align it seems to be a coin toss as to whether it will actually work. I know it has to be applied to inline elements. I have read that I must specify a line-height for elements that do not normally have one. I have read that the height property must have a static (non-auto/non-%) value. I have read that some (modern) browsers do not handle vertical-align correctly if the element they are used on is not naturally an inline element. I am unclear on whether vertical-align should be on the containing element (like text-align) or the element I want vertically aligned.

我创建了这个jsfiddle 尝试解决问题,但仍然感到困惑。

I've created this jsfiddle to try to work out the problem, but remain confused.

#outer {
  box-sizing: border-box;
  border: red 1px solid;
  height: 200px;
  width: 400px;
  text-align: center;
}

#inner {
  border: blue 1px solid;
  display: inline-block;
  height: 200px;
  vertical-align: middle;
}
    
#header {
  border: green 1px solid;
  display: inline-block;
  line-height: 1em;
  margin: 0;
}

<div id="outer">
  <div id="inner">
    <h1 id="header">
      Some Text
    </h1>
  </div>
</div>

在jsfiddle中以上,我希望 #header 会位于 #outer #inner 。显然不是这样。

In the jsfiddle above I would expect #header to be centered halfway between the top and bottom of #outer and #inner. Obviously, that's not the case.

推荐答案

简单地说: vertical-align 仅当应用于该元素的元素具有显示:行内块ìnline时才处于活动/有效状态如果要将一堆图像的顶部边框对齐,则此示例很有用:将它们定义为内嵌块并应用 vertical-align:top

Simply said: vertical-align is only active/valid when the element it is applied to has display: inline-block or ìnline, which for example is useful if you want to align a bunch of images at their top border: You define them as inline-blocks and apply vertical-align: top to them

这里是一个示例:

.wrapper {
  height: 250px;
  border: 1px solid green;
}

.wrapper>img {
  display: inline-block;
  vertical-align: top;
}

<div class="wrapper">
  <img src="https://placehold.it/120x40">
  <img src="https://placehold.it/70x140">
  <img src="https://placehold.it/80x60">
  <img src="https://placehold.it/60x140">
</div>

在您的小提琴中,元素嵌套在一起,而不是彼此相邻,即它们不是兄弟姐妹-每个元素只有一个子元素,因此没有兄弟姐妹的对齐方式在上面的示例中。

In your fiddle, the elements are nested into each other, not next to each other, i.e. they are not siblings - there is only one child element each, so there is no alignment of siblings like in the example above.

这篇关于垂直对齐属性如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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