[英]Position image center of div whetever image size
I have in a problem with centering an image.Hence I have many div and in every div have two div that is divided into two.In those two div I will show two image.Each of these two div is 300 pixel.Problem is images may be small or 300 pixel and I have to show images center if small and if image is 300 then automatically sit on full div. 我有一个问题,居中一个image.Hence我有很多div,在每个div有两个div分为两个。在这两个div我会显示两个图像。这两个div中的每一个是300像素。问题是图像可能是小的或300像素,我必须显示图像中心如果小,如果图像是300然后自动坐在完整div。 Can anyone help me to do this?
任何人都可以帮我这样做吗?
Here is the code.. 这是代码..
<div style="margin-top:10px;height: 300px;width: 600px;background: whitesmoke">
<div style="float:left;width: 300px;height: 300px;">
<img class="" src="images/productImages/medium/<?php echo $product1['product_image']?>" alt="image_01" width="" height="" />
</div>
<div style="float:right;width: 300px;height: 300px;">
<?php if(!empty($product2)) { ?>
<img class="" src="images/productImages/medium/<?php echo $product2['product_image']?>" alt="image_02" width="" height="" />
<?php } ?>
</div>
</div>
you have to position the parent with "relative" and than you can handle the IMGs with position "absolute" ;) 你必须用“亲戚”来定位父母,而你可以处理位置为“绝对”的IMG;)
take a look at this fiddle 看看这个小提琴
.CenterMe {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
You should use display: table-cell;
你应该使用
display: table-cell;
for the parent element and than use max-height
and max-width
properties for your img
tag.. This way you can align the images vertically as well as horizontally. 对于父元素,而不是使用
img
标记的max-height
和max-width
属性。这样,您可以垂直和水平对齐图像。
div {
width: 300px;
height: 300px;
display: table-cell;
border: 1px solid #f00;
text-align: center;
vertical-align: middle;
}
div img {
max-height: 100%;
max-width: 100%;
}
But if you are looking to align images only horizontally and not vertically, than you won't need to do much, just declare text-align: center;
但是如果你想要只是水平而不是垂直对齐图像,那么你就不需要做太多,只需要声明
text-align: center;
on the parent element. 在父元素上。
Use image as background and set position to center: 使用图像作为背景并将位置设置为居中:
<div style="margin-top:10px;height: 300px;width: 600px;background: whitesmoke">
<div style="float:left; width: 300px; height: 300px; background-image: url('images/productImages/medium/<?php echo $product2['product_image']?>'; background-position: center center; background-repeat: no-repeat;">
</div>
<!-- etc. -->
</div>
just add text-align:center
to your image container: 只需将
text-align:center
添加到图像容器:
<div style="float:left;width: 300px;height: 300px; text-align:center">
<img class="" src="images/productImages/medium/<?php echo $product1['product_image']?>" alt="image_01" width="" height="" />
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.