如果您不知道图像的大小,请在Div内垂直和水平居中图像?

Lan*_*ard 12 html javascript css image center

如果我有一个固定大小的容器div和一个未知大小的图像,我该如何水平和垂直居中?

  • 使用纯css
  • 如果css无法使用JQuery

这个答案固定宽度图像有意义,但不是可变宽度图像.

像这样的结构(我想到项目渲染器类似于列表中的这些,但左侧的图像并不总是相同的大小:

<ul id="gallery">
    <li id="galleryItem1">
        <div class="imageContainer">
            <img src="gallery/image1"/>
        </div>
        <p>Some text to the right...</p>
        <!-- more stuff -->
    </li>
    <li id="galleryItem2">
    <!-- ... -->
</ul>
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

小智 6

如果将图像设置为背景图像并以此方式居中不是一个选项,那么jQuery可以调整您为静态图像链接的答案:

$(".fixed-div img.variable").each(function(){
  //get height and width (unitless) and divide by 2
  var hWide = ($(this).width())/2; //half the image's width
  var hTall = ($(this).height())/2; //half the image's height, etc.

  // attach negative and pixel for CSS rule
  hWide = '-' + hWide + 'px';
  hTall = '-' + hTall + 'px';

  $(this).addClass("js-fix").css({
    "margin-left" : hWide,
    "margin-top" : hTall
  });
});
Run Code Online (Sandbox Code Playgroud)

假设CSS类定义为

.variable.js-fix {
  position:absolute;
  top:50%;
  left:50%;
}
Run Code Online (Sandbox Code Playgroud)

固定宽度div具有高度并position:relative声明.

[重要的js编辑:将'.style()'切换为'.css()']


Wol*_*lph 5

你可以用background-position它.

#your_div {
    background-position: center center;
    background-image: url('your_image.png');
}
Run Code Online (Sandbox Code Playgroud)


edt*_*ech 5

Crossbrowser解决方案

<style>
  .border {border: 1px solid black;} 
</style>
<div class="border" style="display: table; height: 400px; width: 400px; #position: relative; overflow: hidden;">
  <div class="border" style=" #position: absolute; #top: 50%;display: table-cell; text-align: center; vertical-align: middle;">
    <div class="border" style="width: 400px; #position: relative; #top: -50%">
      <img src="smurf.jpg" alt="" />
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

垂直div定位的原始解决方案