强制图像始终保持在div的中间

时间:2016-05-10 01:25:30

标签: html css image alignment center

我正在寻找强制图像元素始终在div中间保持对齐的方法,即使div元素太小而无法正确居中图像。以下是我想要做的解释:Question.jpg

如果可能,我需要解决方案纯粹是CSS吗?

4 个答案:

答案 0 :(得分:2)

使用这个居中技巧应该可以满足您的需求:

img {
  position:relative; (or absolute, it depends on your needs)
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
}

无论图像容器的大小如何,都可以使图像保持居中。但它并没有调整图像的大小。基于那张照片,你似乎并不想要那个。

答案 1 :(得分:1)

使用以下网格布局和样式:

 style{
    .container{ max-width:800px; margin:0 auto;}

}

@media
only screen and (max-width:600px) {
.mCenter{margin:0 auto;}
.mImage600:{width:100%; height:auto;}
}

<div class=container>
<div class=mCenter>
<img class=mImage600 src 'img.jpg' width=600 >
</div>
<div>

答案 2 :(得分:0)

你可以这样做,使用display flex

&#13;
&#13;
div {
  width: 100%;
  height: 500px;
  border: 1px solid gray;
  display: flex;
  align-items: flex-start;
  text-align: center;
}
img {
  align-self: center;
  margin: 0 auto;
}
&#13;
<div>
  <img src="http://screenshots.en.sftcdn.net/en/scrn/323000/323026/angry-birds-theme-02-100x100.png" alt="">
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

Fiddle

img{
    margin: 0 auto;
}

可以提供帮助