垂直对齐显示中的多行跨度文本:内联块元素

时间:2015-12-25 18:30:43

标签: html css

我对此代码有疑问,因为lorem ipsum不在父div的中间:

<div style="width: 500px; height: 500px; background-color: #f0f0f0">
    <div style="display: inline-block; width: 100px; height: 100px; background-color: red">
        <a style="vertical-align: middle">lorem ipsum</a>
    </div>
    <div style="display: inline-block; width: 100px; height: 100px; background-color: red">
        <a style="vertical-align: middle">lorem ipsum</a>
    </div>
</div>

我知道,我可以使用table-cell和许多其他方法,但为什么像我这样的简单代码不起作用?有解决方案吗?我需要IE8支持和多行支持,position: absolute不是解决方案......

3 个答案:

答案 0 :(得分:2)

尝试提供line-height: 100px代替vertical-align。你可以这样使用:

&#13;
&#13;
<div style="width: 500px; height: 500px; background-color: #f0f0f0">
  <div style="display: inline-block; width: 100px; height: 100px; background-color: red">
    <a style="line-height: 100px;">lorem ipsum</a>
  </div>
  <div style="display: inline-block; width: 100px; height: 100px; background-color: red">
    <a style="line-height: 100px;">lorem ipsum</a>
  </div>
</div>
&#13;
&#13;
&#13;

预览

或者下一种方法是使用仅适用于现代浏览器的translate

&#13;
&#13;
<div style="width: 500px; height: 500px; background-color: #f0f0f0">
  <div style="display: inline-block; width: 100px; height: 100px; background-color: red; position: relative;">
    <a style="transform: translate(-50%, -50%); top: 50%; left: 50%; position: absolute;">lorem ipsum</a>
  </div>
  <div style="display: inline-block; width: 100px; height: 100px; background-color: red; position: relative;">
    <a style="transform: translate(-50%, -50%); top: 50%; left: 50%; position: absolute;">lorem ipsum</a>
  </div>
</div>
&#13;
&#13;
&#13;

预览

答案 1 :(得分:2)

这是小提琴,使用vertical-align:middle

https://jsfiddle.net/kodedsoft/txgLzycd/

代码是

<div style="width: 500px; height: 500px; background-color: #f0f0f0">
    <div style="display: table;vertical-align:middle; width: 100px; height: 100px; background-color: red">
        <a style="display:table-cell;vertical-align: middle">lorem ipsum</a>
    </div>
    <div style="display: table;vertical-align:middle; width: 100px; height: 100px; background-color: red">
        <a style="display:table-cell;vertical-align: middle">lorem ipsum</a>
    </div>
</div>

**更新: https://jsfiddle.net/kodedsoft/txgLzycd/3/ **

答案 2 :(得分:0)

Vertical-align并不代表我认为您的意思。

在这个例子中,vertical align指的是元素相对于兄弟姐妹的对齐 ...不在父母中(除非它是表格或表格单元格)(或其他祖先) )。

但是,你真的不需要它,因为......

Flexbox可以做到这一点:

&#13;
&#13;
.parent {
  width: 500px;
  height: 200px;
  background-color: #f0f0f0;
  text-align: center;
  margin: 1em auto;
  border: 1px solid grey;
  display: flex;
  justify-content: center;
  align-items: center;
}
.child {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 100px;
  background-color: red
}
a {
  text-decoration: none;
}
&#13;
<div class="parent">
  <div class="child">
    <a href="#">lorem ipsum</a>
  </div>
  <div class="child">
    <a href="#">lorem ipsum</a>
  </div>
</div>
&#13;
&#13;
&#13;