下面是div

<div id="over" style="position:absolute; width:100%; height:100%>
 <img src="img.png">
</div>

如何对齐图像,使其位于div的中间和中心?


当前回答

这招对我很管用。

<div class="CenterImage">
         <asp:Image ID="BrandImage" runat="server" />
</div>

注意:在这种情况下,没有与'BrandImage'相关的css类

CSS:

.CenterImage {
    position:absolute; 
    width:100%; 
    height:100%
}

.CenterImage img {
    margin: 0 auto;
    display: block;
}

其他回答

一个简单的方法是为div和图像创建单独的样式,然后分别放置它们。比方说,如果我想将图像位置设置为50%,那么我将有如下代码....

在{# 位置:绝对的; 宽度:100%; 高度:100%; } # img { 位置:绝对的; 左:50%; 右:50%; } < div id = " / " > <img src="img.png" id="img"> < / div >

现在是2016年……为什么不使用flexbox? 它的反应也很灵敏。享受。 在{# 显示:flex; 对齐项目:中心; justify-content:中心; } < div id = " / " > < img src = " http://www.garcard.com/images/garcard_symbol.png " > < / div >

水平放置

#over img {
    display: block;
    margin: 0 auto;
    clear:both;
}

另一种方法:

#over img {
    display: inline-block;
    text-align: center;
}

只需要放置:

   #over img {

           vertical-align: middle;
        }

在我看来,您还希望图像在容器中垂直居中。(我没有看到任何答案提供了这一点)

工作小提琴:

纯CSS解决方案 不中断文档流(没有浮动或绝对定位) 跨浏览器兼容性(甚至包括IE6) 完全响应。

HTML

<div id="over">
    <span class="Centerer"></span>
    <img class="Centered" src="http://th07.deviantart.net/fs71/200H/f/2013/236/d/b/bw_avlonas_a5_beach_isles_wallpaper_image_by_lemnosexplorer-d6jh3i7.jpg" />
</div>

CSS

*
{
    padding: 0;
    margin: 0;
}
#over
{
    position:absolute;
    width:100%;
    height:100%;
    text-align: center; /*handles the horizontal centering*/
}
/*handles the vertical centering*/
.Centerer
{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.Centered
{
    display: inline-block;
    vertical-align: middle;
}

注意:此解决方案适用于在任何元素中对齐任何元素。 对于IE7,当在块元素上应用.居中类时,你将不得不使用另一个技巧来让内联块工作。(这是因为IE6/IE7不能很好地使用内联块对块元素)

很长一段时间,我也尝试了解决方案,把img放在div的中心,但对于我的情况下,我只需要这种类型的组件在ajax加载进度,所以我简单地尝试了以下解决方案,希望这对你有帮助!

<div id="loader" style="position: absolute;top: 0;right: 0;left: 0;bottom: 0;z-index: 1;background: rgba(255,255,255,0.5) url('your_image_url') no-repeat center;background-size: 135px;display: none;"></div>