Lan*_*ard 12 html javascript css image center
如果我有一个固定大小的容器div和一个未知大小的图像,我该如何水平和垂直居中?
像这样的结构(我想到项目渲染器类似于列表中的这些,但左侧的图像并不总是相同的大小:
<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()']
你可以用background-position它.
#your_div {
background-position: center center;
background-image: url('your_image.png');
}
Run Code Online (Sandbox Code Playgroud)
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)