是否可以将绝对定位的img水平居中?

时间:2015-03-19 16:47:50

标签: css

是否有可能,仅使用CSS(无JS),使图像水平居中于其容器,以类似响应的方式(显然,如果容器具有固定的宽度,我可以使用像素进行数学计算得到它确切)??

以下是该场景的小提琴:http://jsfiddle.net/uqxu0vtv/1/

div.somediv { padding: 150px 2% 2%; border: 1px solid #000; position: relative;}
    div.somediv img { position: absolute; top: 20px; left: 35%;} 

1 个答案:

答案 0 :(得分:1)

是的,绝对! :)

div.somediv {
  padding: 150px 2% 2%;
  border: 1px solid #000;
  position: relative;
}
div.somediv img {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
}
<div class="somediv">
  <img src="http://blog.grio.com/wp-content/uploads/2012/09/stackoverflow.png" />
  <p>If the Federal Reserve prints more money, then the market will go up in nominal terms, creating the illusion that the stock market is going up, but it's not; our money is going down.</p>
</div>