如何获得img垂直中间?

时间:2015-02-19 22:42:36

标签: html css html5

我有以下代码



.topic {
  float: left;
  width: 500px;
}
.topic .tInfo {
  float: left;
  width: 460px;
}
.topic .tName {
  width: 460px;
}
.topic .tTime {
  width: 460px;
}
.topic .tUImgLnk {
  width: 400px;
  height: 400px;
  float: left;
  background-color: red;
}
.topic .tUImgLnk .tUImg {
  margin: 0px auto;
  display: block;
  vertical-align: middle;
}

<div class="topic" data-reactid=".yvg4g1tbeo.0.$1">
  <div class="tUImgLnk" data-reactid=".yvg4g1tbeo.0.$1.0">
    <a title="test" target="_blank" href="http://www.test.net" data-reactid=".yvg4g1tbeo.0.$1.0.0">
      <img class="tUImg" src="http://www.easyvectors.com/assets/images/vectors/vmvectors/dekstop-computer-vector-26.jpg" data-reactid=".yvg4g1tbeo.0.$1.0.0.0">
    </a>
  </div>
</div>
&#13;
&#13;
&#13;

如何让它垂直居中?我试图将容器设置为vertical-align:middle,但这没有帮助。

3 个答案:

答案 0 :(得分:1)

给出主题&#39;图像作为背景,因为你有一个覆盖div的链接它不应该是一个问题。

http://jsfiddle.net/q3x1Lmzg/1/

.topic .tUImgLnk {
  width: 400px;
  height: 400px;
  float: left;
  background: url(http://www.easyvectors.com/assets/images/vectors/vmvectors/dekstop-computer-vector-26.jpg) no-repeat ;
    background-position: center;
    background-size: 350px;
    background-color:red;
}

答案 1 :(得分:1)

尝试按照,使用上/下设置和转换。

&#13;
&#13;
.topic {
  float: left;
  width: 500px;
}
.topic .tInfo {
  float: left;
  width: 460px;
}
.topic .tName {
  width: 460px;
}
.topic .tTime {
  width: 460px;
}
.topic .tUImgLnk {
  width: 400px;
  height: 400px;
  float: left;
  background-color: red;
}
.topic .tUImgLnk .tUImg {
  margin: 0px auto;
  display: block;
  }

.tUImgLnk {
   position: relative;     
  }

.tUImg {
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
  position: absolute;  
}
&#13;
<div class="topic" data-reactid=".yvg4g1tbeo.0.$1">
  <div class="tUImgLnk" data-reactid=".yvg4g1tbeo.0.$1.0">
    <a title="test" target="_blank" href="http://www.test.net" data-reactid=".yvg4g1tbeo.0.$1.0.0">
      <img class="tUImg" src="http://www.easyvectors.com/assets/images/vectors/vmvectors/dekstop-computer-vector-26.jpg" data-reactid=".yvg4g1tbeo.0.$1.0.0.0">
    </a>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

2个非常简单的解决方案。

更复杂(但很简单):JSFiddle

/*Table takes everything inside it and lays it out on a grid.*/
.table {
    background-color:red;
    height:400px;
    width:400px;
    text-align:center;
    display: table;
}
/*each cell is positioned by the table to be vertical aligned */
.cell {
    display: table-cell;
    vertical-align: middle;
}

非常简单:JSFiddle

/*just add padding*/
 .pad {
    display:inline-block;
    background-color:red;
    padding: 30px;
}