0

请参阅下面的代码,图像和文本都位于 div 中。如何使用纯css垂直对齐中间的图像(div_a)和文本(div_txt)<a>,并保持div可点击(具有跨浏览器兼容性的首选解决方案):

<style type="text/css">
  a.div_a {
      display:block;
      width:320px;
      height:160px;
      background-color:#CCC;}
</style>

<a href="www.mydoamin.com" class="div_a">
  <img src="http://jsfiddle.net/img/logo.png" style="float:left; margin-right:10px; background-color:#666;" />
  <span class="div_txt">Content</span>
</a>

我尝试了以下方法,但这没有帮助:

.div_txt {vertical-align:middle;}

我在上面为图像/文本找到了单独的解决方案,但不是同时用于两者。

4

2 回答 2

1

取自Vertical-align 图像并稍作修改以说明<a>jsFiddle 演示):

链接的额外标记

a.absoluteCenterWrapper {
 display:block;
}

CSS

.absoluteCenterWrapper {
 position:relative; /* Contains the image in the div */
}

/* Positioning */
.absoluteCenter {
 margin:auto; /* Required */
 position:absolute; /* Required */
 top:0;bottom:0; /* Aligns Vertically */
}

/* Sizing - resizes down to avoid cutting off */
.absoluteCenter { /* Fallback Sizing */
 max-height:100%;
 max-width:100%;
}

HTML

<a href="http://www.example.com/" class="absoluteCenterWrapper">
 <img src="PATHTOIMAGE" class="absoluteCenter">
 <p>Paragraph goes here.</p>
</a>
于 2013-02-18T20:57:04.883 回答
1

display: table您的锚元素,然后将每个图像和跨度包装在.wrapper具有以下属性的跨度中:

.wrapper {
  display: table-cell;
  vertical-align: middle;
}

HTML:

<a href="www.mydoamin.com" class="div_a">
  <span class="wrapper">
    <img src="http://jsfiddle.net/img/logo.png" style="background-color:#666;" />
  </span>

  <span class="wrapper">
    <span class="div_txt">Content</span>
  </span>
</a>

演示

请注意,这种方法在 IE7 中不起作用,因此如果需要 IE7 支持,您将不得不使用更复杂的方法。

于 2013-02-18T21:00:40.973 回答