简体   繁体   English

我如何使图像进入div的中心?

[英]How do I get my image to go in the center of the div?

Given this HTML: 鉴于此HTML:

<div>
  <img id="image">
</div>

How do I get the image to go in the center of the div? 我如何使图像进入div的中心?

At the moment it is located in the top left of the div. 目前,它位于div的左上方。

I tried 我试过了

img#image
{
    text-align:center;
}

But it made no difference. 但这没什么区别。

Try giving position relative to div: 尝试给出relative对于div的位置:

#div_id{
  position:relative;
  width:400px;
  height:200px;
}

and this CSS for image: 以及此CSS图片:

#img_id{
  position:absolute;
  top:100px; /* half of parent div's height */
  left:200px;  /* half of parent div's width */
  display:block;
}

You need to set the text-align on the container like: 您需要像设置容器上的文本对齐:

<div class="image">
  <img />
</div>    

div.image {
   text-align: center;
}

More info here: http://www.gtalbot.org/NvuSection/NvuWebDesignTips/HorizontalAlignment.html 此处提供更多信息: http : //www.gtalbot.org/NvuSection/NvuWebDesignTips/Horizo​​ntalAlignment.html

<img style='display:block; margin:0 auto' src='...'>

将图像居中放置在容器中

CSS: CSS:

div { text-align: center; }
#image { display: inline-block; vertical-align: middle; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM