< div>中的垂直对齐中间 [英] vertical align middle in <div>

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

问题描述

我想将#abc div的高度保持在50px,并且文本在div的中间垂直对齐.

I want to keep the height of #abc div at 50px and text to align vertically in the middle of the div.

body{
  padding: 0;
  margin: 0;
  margin: 0px auto;
}

#main{
  position: relative;
  background-color:blue;
  width:500px;
  height:500px;
}

#abc{
  font:Verdana, Geneva, sans-serif;
  font-size:18px;
  text-align:left;
  background-color:#0F0;
  height:50px;
  vertical-align:middle;
}

<div id="main">
 <div id="abc">
     asdfasdfafasdfasdf
 </div>
</div>

推荐答案

您可以使用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.

这篇关于&lt; div&gt;中的垂直对齐中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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