垂直和水平将图像居中在Div中,如果您不知道图像的大小? [英] Vertically and Horizontally Center Image inside a Div, if you don't know Image's Size?

查看:172
本文介绍了垂直和水平将图像居中在Div中,如果您不知道图像的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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







这个回答对于固定的

图片,但不是可变图片。



这样的结构(我记得与列表中的类似的项目渲染器,但左侧的图片不一定是相同的大小:

 < ul id =gallery> 
< li id =galleryItem1>
< div class =imageContainer>
< img src =gallery / image1/>
< / div>
< p>一些文字向右...< / p>
<! - more stuff - >
< / li>
< li id =galleryItem2>
<! - ... - >
< / ul>

感谢您的帮助!

解决方案

如果将图像设置为背景图片,并且它的方式是不是一个选项,jQuery来适应您为静态图片链接的答案将会出现:

  $(。fixed-div img.variable)。each(function(){
//获取高度和宽度$ b var hWide =($(this).width())/ 2; //图片宽度的一半
var hTall =($(this).height())/ 2; ,等等

//为CSS规则附加负数和像素
hWide =' - '+ hWide +'px';
hTall =' - '+ hTall +'px ';

$(this).addClass(js-fix)css({
margin-left:hWide,
margin-top:hTall
});
});假定一个CSS类定义为



<$ p


$ p> .variable.js-fix {
position:absolute;
top:50%;
left:50%;
}

其中固定宽度div具有高度和位置:相对



[important js edit:switched'.style()'to'.css()']


If I have a fixed sized container div, and an unknown sized image, how do I horizontally and vertically center it?

  • using pure css
  • using JQuery if css can't do it

This answer makes sense for fixed width images, but not variable ones.

Something like this structure (I have in mind item renderers similar to these in the list, but where the image on the left wouldn't always be the same size:

<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>

Thanks for the help!

解决方案

If setting the image as a background image and centering it that way isn't an option, the jQuery to adapt the answer you linked for static images would go:

$(".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
  });
});

assuming a CSS class defined as

.variable.js-fix {
  position:absolute;
  top:50%;
  left:50%;
}

with the fixed-width div having a height and position:relative declared.

[important js edit: switched '.style()' to '.css()']

这篇关于垂直和水平将图像居中在Div中,如果您不知道图像的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆