如果父级较小,如何保持图像居中?

时间:2014-09-08 13:02:30

标签: html css

我目前正在尝试应对设计。 我需要在父div变小的同时保持图像居中。

见图片解释:enter image description here

我不想用它作为背景。 以下代码将始终将其放在div框的左上角

<div id="img_wrap">
    <img src="test.png" id="img" />
</div>

<style type="text/css">
    #img_wrap {
        overflow: hidden;
        text-align: center;
    }
</style>

4 个答案:

答案 0 :(得分:2)

这是example

#img_wrap{
  position: relative;
  overflow: hidden;

  /* arbitrary container size */
  width: 7rem; 
  height: 16rem;
}

#img{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
}

诀窍是图像绝对位于中心,占其父容器宽度的50%,然后通过变换向左移动50%的自身宽度。

答案 1 :(得分:0)

如果旧浏览器兼容性不是问题,您可以使用以下

#img_wrap img
{
   display:flex;
   -ms-flex-pack:stretch;
   -webkit-box-pack:stretch;
   justify-content:center;
}

答案 2 :(得分:0)

用于制作图像中心

<div id="img_wrap">
    <img src="http://placehold.it/350x150" id="img" />
</div>


<style type="text/css">
       #img_wrap{  
         position: relative;
        width: 200px;
         height:150px;/*give the image height*/
        background: red;
        overflow:hidden;
       display: inline-block;
    }

    #img{
      position: absolute;
     left: 50%;
     transform: translateX(-50%);
   }
    </style>

以下是演示http://jsfiddle.net/adarshkr/p1p100h7/1/

答案 3 :(得分:-1)

这是解决方案,使图像响应..

<div id="img_wrap">
    <img src="test.png" id="img" />
</div>

<style type="text/css">


      #img_wrap{
        position:relative
        }
    #img_wrap img{
       max-width:100%;
       height:auto;
       margin:0 auto;
       display:block;


    }
</style>

希望它有所帮助...