div垂直对齐中间css [英] div vertical align middle css

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

问题描述

我想让我的文本垂直对齐到abc div的div的中间。
我想保持高度为50,文本在div的中间垂直对齐。
我还没有找到解决这个问题的方法,也许不是正确的东西。



http://jsfiddle.net/79x2a/22/

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


解决方案

$ c> line-height:50px; ,你不需要 vertical-align:middle;



演示






如果你有多行,上面的命令就会失败,所以在这种情况下你可以使用 span display:table-cell; display:table; align:middle; ,也不要忘记使用 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 和以后的位置 50%顶部转换为负轴 -50%

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

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

演示



请注意,旧版浏览器(例如IE8)不支持此功能,其他旧浏览器版本的Chrome和Firefox分别使用 -ms,-moz -webkit 前缀。 >

有关 transform 的更多信息,您可以参考此处


I'm trying to get my text to vertically align to the middle of the div of the abc div only. i want to keep the height at 50 and text to align vertically in the middle of the div. i've yet to find a solution to this problem, maybe im not searching the right things.

http://jsfiddle.net/79x2a/22/

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

解决方案

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

Demo


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

Demo

#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;
}


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%);
}

Demo

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.

For more information on transform, you can refer here.

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

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