IE8仅使用css对齐跨度垂直居中的图像?

时间:2017-02-04 09:29:40

标签: html css html5 css3 internet-explorer-8

我想在IE8中将span标签垂直对齐图像标签和上面的图像。

我有这样的DOM:

    <div class="parent">
      <img src="pathToImage"/>
      <span>Align this text to vertical center</span>
   </div>

很高兴回答。

2 个答案:

答案 0 :(得分:1)

如果span具有已知高度(文本/行数),您可以向下浮动图像并让span移动到图像释放的区域:

&#13;
&#13;
.parent:before {
  content: '';
  float: left;
  height: 2em;/* at least enough for one line of text */
}
img {
  float: left;
  clear: left;
}
&#13;
<div class="parent">
  <img src="http://placehold.it/100" />
  <span>Align this text to vertical center</span>
</div>
&#13;
&#13;
&#13;

要过滤IE8,您可以使用the conditionnal comments from IE toolbox <!--[if IE8]><style>/* styles here */</style><[endif]-->,对于任何旧版浏览器,您可以通过flex覆盖此浮动行为:

&#13;
&#13;
.parent:before {
  content: '';
  float: left;
  height: 2em;
}
img {
  float: left;
  clear: left;
}
.parent {
  display: flex;
  align-items: center;
}
&#13;
<div class="parent">
  <img src="http://placehold.it/100" />
  <span>Align this text to vertical center</span>
</div>
&#13;
&#13;
&#13;

...

我仍然没有看到它的重点?

过滤IE8的另一种方法

&#13;
&#13;
body:before {
  content:'IE8';
  }
body::before {
  content:'NOT IE8';
  }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我可以使用现有标记得到最接近的,使用position: absolute将其置于中心

.parent {
  display: inline-block;
  position: relative;
}
.parent span {
  margin: auto;
  position: absolute;
  height: 22px;
  width: 150px;
  left: 0; top: 0; bottom: 0; right: 0;
  color: white;
}
<div class="parent">
  <img src="http://placehold.it/200" />
  <span>Align to vertical center</span>
</div>

根据评论更新

动态文字(1行或更多行)的唯一CSS方式是合并display: tableposition: absolute

Stack snippet

.parent {
  display: inline-block;
  position: relative;
}
.parent > div {
  position: absolute;
  left: 0; top: 0; bottom: 0; right: 0;
}
.parent > div > div {
  display: table;
  width: 100%;
  height: 100%;
}
.parent span {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  color: white;
}
<div class="parent">
  <img src="http://placehold.it/200" />
  <div>
    <div>
      <span>Align to vertical center,<br>
      even with 2 lines</span>
    </div>
  </div>
</div>