如何使用CSS在HTML中垂直居中一个图像到一个div元素中?

68

我有这样的标记:

<div>
  <img />
</div>
元素比元素高:
div {
  height: 100px;
}

img {
  height: dynamic-value-smaller-than-100px;
}

我需要图片位于div中央(上下有相同数量的空白)。 我尝试过以下方法,但并不起作用:
div {
  vertical-align: middle;
}

这里有两种简单的方法可以在div中垂直、水平或同时居中对象(纯CSS):https://dev59.com/bmct5IYBdhLWcg3wmOZN#31977476 - Michael Benjamin
16个回答

73

如果您的图片仅用作装饰,那么将其用作背景图像可能是更语义化的解决方案。您可以指定背景图像的位置。

background-position: center center;

如果图片不是装饰性的,而是包含有价值的信息,那么使用img标签是合理的。在这种情况下,您需要使用以下属性样式化包含图片的div:

div{
    display: table-cell; vertical-align: middle 
}

在此处阅读更多关于这种技术的信息。据报道,在IE6/7上无法运行(在IE8上可以)。


这不是装饰性的。实际上,我正在构建一个公司标志列表,它们可以作为链接使用,但无论如何这是个好主意。 - Josef Sábl
太好了,它起作用了!请添加信息,说明这个CSS必须添加到div而不是img,这有点让我困惑。非常感谢。 - Josef Sábl
4
请注意,这在IE6和IE7中无法运行(不确定IE8)。 - Matteo Riva

55

另一种方法是在容器div中设置行高(line-height),并使用vertical-align: middle将图像对齐到该行高。

html:

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

层叠样式表:

.container {
  width: 200px; /* or whatever you want */
  height: 200px; /* or whatever you want */
  line-height: 200px; /* or whatever you want, should match height */
  text-align: center;
}

.container > img {
  vertical-align: middle;
}

这只是我的初步想法。但我之前用过这个方法-应该可以解决问题。它也适用于旧版本的浏览器。


2
就我所知,这是目前最好的解决方案。很奇怪它在页面上排名第二。它很容易实现,并且适用于所有浏览器。已经在各种IE老版本中进行了测试,表现良好。谢谢! - Warre Buysse
这个应该是被接受的答案。与display: table-cell;相比,这个解决方案会带来更多的痛苦。 - trushkevich

9

假设你想要将一张 40px X 40px 的图片放在 div class="box" 的中央(水平和垂直方向上)。那么你需要使用以下的 HTML 代码:

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

您需要做的是应用CSS:

.box img {
    position: absolute;
    top: 50%;
    margin-top: -20px;
    left: 50%;
    margin-left: -20px;
}

您的div甚至可以改变大小,图片始终位于其中心。


为什么这不是最佳答案?我在想。太好了,而且简单!;-) - Dr.Kameleon

5

这是我之前用来在CSS中实现垂直居中的解决方案。这在所有现代浏览器中都可以使用。

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

摘录:

  <div style="display: table; height: 400px; position: relative; overflow: hidden;">
    <div style="position: absolute; top: 50%;display: table-cell; vertical-align: middle;">
      <div style="position: relative; top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>

(用于演示目的的内联样式)


3
另一种选择是在元素上设置display:block,然后设置margin: 0px auto;。
img{
    display: block;
    margin: 0px auto;
}

1
适用于水平居中图像的代码;问题是关于垂直居中的。 - Marc Rochkind

2

使用纯CSS有五种可能的方法来使任何大小的图像居中。

  1. Using flex and making the img tag be inside (best solution for modern browsers):

    div {
        display: flex;
        align-items: center;
        justify-content: center
    }
    
  2. Putting the image in background-image and using background-position (as @pixeline explained):

    div {
        background-image: url(...);
        background-position:center center
    }
    
  3. Using display: table for parent element, and using display: table-cell with vertical-align: middle for child element:

    div.parent {
        display: table;
    }
    div.child {
        display: table-cell;
        vertical-align: middle;
    }
    
  4. Using position:absolute with transform for the image and parent element position be not unset:

    div {
        position: relative;
    }
    div > img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }
    
  5. Using line-height as same height of the element, then using vertical-align (in my opinion, the best solution for supporting more browsers like IE9>).

    Note: In some old browsers, sometimes for using this way safely, you need to have at least one character in the line that the image exist. For fixing this issue, I used a non-breakable space in a pseudo-element of the parent.

    As in the following example:

    div {
        display: block;
        height: 200px;
        width: 200px;
        background-color: purple;
        line-height: 200px;
        text-align: center;
    }
    div:after {
      content: "\a0";
    }
    div > img {
        vertical-align: middle;
    }
    <div><img src="https://via.placeholder.com/100.png/09f/fff" /></div>


2

由于跨浏览器的CSS常常让我失望,我想在这里提供一个jQuery解决方案。这个方案获取每个图片父元素div的高度,将其除以二,并将结果设置为图片与div之间的顶部边距:

$('div img').each(function() {
 m = Math.floor(($(this).parent('div').height() - $(this).height())/2);
 mp = m+"px";
 $(this).css("margin-top",mp);
});

1

图片应该在div的中间

div img{ 
    bottom: 0;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    top: 0;
    height:50px;
    width:50px;
}

我阅读并尝试了这里的所有答案... 这是对我有效的答案! - c0x6a

1

我已经发布了关于跨浏览器垂直对齐的帖子(使用CSS垂直居中多个框

创建一个单元格表格。只有表格具有跨浏览器的垂直对齐。


0
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
(function ($) {

$.fn.verticalAlign = function() {
    return this.each(function(i){
    var ah = $(this).height();
    var ph = $(this).parent().height();
    var mh = Math.ceil((ph-ah)/2);
    $(this).css('margin-top', mh);
    });
};
})(jQuery);

$(document).ready(function(e) {


$('.in').verticalAlign();


});

</script>

<style type="text/css">
body { margin:0; padding:0;}
.divWrap { width:100%;}
.out { width:500px; height:500px; background:#000; text-align:center; padding:1px; }
.in { width:100px; height:100px; background:#CCC; margin:0 auto; }
</style>
</head>

<body>
<div class="divWrap">
<div class="out">
<div class="in">
</div>
</div>
</div>

</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接