且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

< div>中的垂直对齐中间

更新时间:2022-05-24 10:00:20

您可以使用line-height: 50px;,那里不需要vertical-align: middle;.

You can use line-height: 50px;, you won't need vertical-align: middle; there.

演示

如果您有多行内容,则上述操作将失败,因此在这种情况下,您可以使用span换行,然后将display: table-cell;display: table;vertical-align: middle;一起使用,也不要忘记使用width: 100%;表示#abc

The above will fail if you've multiple lines, so in that case you can wrap your text using span and than use display: table-cell; and display: table; along with vertical-align: middle;, also don't forget to use width: 100%; for #abc

演示

#abc{
  font:Verdana, Geneva, sans-serif;
  font-size:18px;
  text-align:left;
  background-color:#0F0;
  height:50px;
  display: table;
  width: 100%;
}

#abc span {
  vertical-align:middle;
  display: table-cell;
}


我在这里可以想到的另一种解决方案是将transform属性与translateY()一起使用,其中Y显然表示Y轴.这很简单...您要做的就是将元素位置设置为absolute,然后将top的位置设置为50%,并使用负的-50%


Another solution I can think of here is to use transform property with translateY() where Y obviously stands for Y Axis. It's pretty straight forward... All you need to do is set the elements position to absolute and later position 50% from the top and translate from it's axis with negative -50%

div {
  height: 100px;
  width: 100px;
  background-color: tomato;
  position: relative;
}

p {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

演示

请注意,较旧的浏览器(例如IE8)将不支持此功能,但是您可以分别使用-ms, -moz-webkit前缀来制作IE9和其他较旧版本的Chrome和Firefox浏览器.

Note that this won't be supported on older browsers, for example IE8, but you can make IE9 and other older browser versions of Chrome and Firefox by using -ms, -moz and -webkit prefixes respectively.

有关transform的更多信息,您可以在此处.

For more information on transform, you can refer here.