Javascript 如果您不知道图像的大小,则在 Div 中垂直和水平居中图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2436986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vertically and Horizontally Center Image inside a Div, if you don't know Image's Size?
提问by Lance Pollard
If I have a fixed sized container div, and an unknown sized image, how do I horizontally and vertically center it?
如果我有一个固定大小的容器 div 和一个未知大小的图像,我如何水平和垂直居中它?
- using pure css
- using JQuery if css can't do it
- 使用纯css
- 如果 css 无法做到,则使用 JQuery
This answer makes sensefor fixed widthimages, 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:
类似于这种结构的东西(我想到了与 list 中的这些类似的项目渲染器,但左侧的图像并不总是相同的大小:
<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!
谢谢您的帮助!
回答by Lance Pollard
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 imageswould go:
如果将图像设置为背景图像并以这种方式居中不是一种选择,那么 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
});
});
assuming a CSS class defined as
假设一个 CSS 类定义为
.variable.js-fix {
position:absolute;
top:50%;
left:50%;
}
with the fixed-width div having a height and position:relativedeclared.
具有高度并position:relative声明的固定宽度 div 。
[important js edit: switched '.style()' to '.css()']
[重要的 js 编辑:将 '.style()' 切换为 '.css()']
回答by Wolph
You could use background-positionfor that.
你可以用background-position它。
#your_div {
background-position: center center;
background-image: url('your_image.png');
}
回答by edtsech
Crossbrowser solution
跨浏览器解决方案
<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>
回答by dmitry
Check out my solution: http://codepen.io/petethepig/pen/dvFsA
查看我的解决方案:http: //codepen.io/petthepig/pen/dvFsA
It's written in pure CSS, without any JS code. It can handle images of any size and any orientation.
它是用纯 CSS 编写的,没有任何 JS 代码。它可以处理任何大小和任何方向的图像。
add another div to your HTML code:
将另一个 div 添加到您的 HTML 代码中:
<div class="imageContainer">
<img src="gallery/image1"/>
</div>
CSS code:
CSS代码:
.imageContainer {
font-size: 0;
text-align: center;
width: 200px; /* Container's dimensions */
height: 150px;
}
img {
display: inline-block;
vertical-align: middle;
max-height: 100%;
max-width: 100%;
}
.imageContainer:before {
content: '';
display: inline-block;
vertical-align: middle;
height: 150px;
}
Update:I got rid of this <div class="trick"></div>element in favor of :beforeCSS selector
更新:我摆脱了这个<div class="trick"></div>元素,转而使用:beforeCSS 选择器
回答by Ricardo Rodriguez
If you dont know the image sizes but you have uploaded the pictures next to the size of the container (maybe bigger or smaller images), this post can be useful. Something that is working for me is the next code:
如果您不知道图像大小,但您已经上传了容器大小旁边的图片(可能更大或更小的图像),这篇文章可能很有用。对我有用的是下一个代码:
<a class="linkPic" href="#">
<img src="images/img1.jpg" alt=""/>
</a>
<a class="linkPic" href="#">
<img src="images/img2.jpg" alt=""/>
</a>
<a class="linkPic" href="#">
<img src="images/img3.jpg" alt=""/>
</a>
And in the .css file you have the next rules:
在 .css 文件中,您有以下规则:
a.linkPic{
position:relative;
display: block;
width: 200px; height:180px; overflow:hidden;
}
a.linkPic img{
position:absolute;
}
You can notice you have an image tag inside the a.linkPic, so first you have to set it as "position:relative" for containing the "img" absolute element. The trick to center the picture without problems is a little jQuery code. Follow the comments to understand what is going on (some lines were taken from the Vladimir Maryasov post in this page):
您会注意到 a.linkPic 中有一个图像标签,因此首先您必须将其设置为“position:relative”以包含“img”绝对元素。使图片居中而不出现问题的技巧是一些 jQuery 代码。按照评论了解正在发生的事情(一些台词摘自本页中 Vladimir Maryasov 的帖子):
$("a.linkPic img").each(function() {
// Get container size
var wrapW = $("a.linkPic").width();
var wrapH = $("a.linkPic").height();
// Get image sizes
var imgW = $(this).width();
var imgH = $(this).height();
// Compare if image is bigger than container
// If image is bigger, we have to adjust positions
// and if dont, we have to center it inside the container
if (imgW > wrapW && imgH > wrapH)
{
// Centrar por medio de cálculos
var moveX = (imgW - wrapW)/2;
var moveY = (imgH - wrapH)/2;
// attach negative and pixel for CSS rule
var hWide = '-' + moveX + 'px';
var hTall = '-' + moveY + 'px';
$(this).addClass("imgCenterInDiv").css({
"margin-left" : hWide,
"margin-top" : hTall
});
} else {
$(this).addClass("imgCenterInDiv").css({
"left" : 0,
"right" : 0,
"top" : 0,
"bottom" : 0,
"margin" : "auto",
});
}//if
});
After this, all the pictures inside in a.linkPic containers will be placed perfectly centered. I Hope this post can be useful for someone!
之后,a.linkPic 容器中的所有图片都将完美居中放置。我希望这篇文章对某人有用!
回答by Rob
This is a PHP variant.
这是一个 PHP 变体。
It is a lot of code but works like a charm. I came up with it after reading several posts on this subject. It positions images of various sizes in een fixed width and height div
它有很多代码,但效果很好。在阅读了关于这个主题的几篇文章后,我想出了它。它将各种尺寸的图像定位在 een 固定宽度和高度的 div 中
You CSS should contain this:
你的 CSS 应该包含这个:
.friend_photo_cropped{
overflow: hidden;
height: 75px;
width: 75px;
position:relative;
}
.friend_photo_cropped img{
position:relative;
}
Your code should be this:
你的代码应该是这样的:
<?php
list($width, $height) = getimagesize($yourImage);
if ($width>=$height)
{
$h = '75';
$w = round((75/$height)*$width);
}
else
{
$w = '75';
$h = round((75/$width)*$height);
}
$top = -round(($h-75)/2);
$left = -round(($w-75)/2);
echo '<td height="75">';
echo '<div class="friend_photo_cropped">';
echo '<img src="'.$yourImage.'" width="'.$w.'" height="'.$h.'" style="top:'.$top.'px;left:'.$left.'px;">';
echo '</div>';
echo '</td>';
?>
回答by vitalyp
You can also align this way. At least thats how i did it and it worked for me. May not be the best way of doing it. I had a bunch of different size logos inside fixed size divs.
你也可以这样对齐。至少我就是这样做的,它对我有用。可能不是最好的方法。我在固定大小的 div 中有一堆不同大小的徽标。
First get the dimensions of the image. Then based on the height of your div you can figure out what the top margin should be. This will vertically center it. Just change $IMG_URL and $DIVHEIGHT values.
首先获取图像的尺寸。然后根据 div 的高度,您可以确定上边距应该是多少。这将垂直居中。只需更改 $IMG_URL 和 $DIVHEIGHT 值。
list($width, $height, $type, $attr) = getimagesize($IMG_URL);
$margin-top = number_format(($DIVHEIGHT - $height) / 2, 0);
For example.
例如。
<div style="margin-top:".$margin-top."px\"><img src="" /> </div>
回答by edtsech
Using display: table-cell trick for div
使用显示:div 的表格单元格技巧
Working correctly in: Firefox, Safari, Opera, Chrome, IE8
可在:Firefox、Safari、Opera、Chrome、IE8 中正常工作
CSS example:
CSS 示例:
div {
width: 300px;
height: 300px;
border: 1px solid black;
display: table-cell;
text-align: center;
vertical-align: middle;
}
img {
display: inline;
}
HTML example:
HTML 示例:
<div>
<span></span>
<img src="" alt="" />
</div>
回答by Vladimir Maryasov
I used
我用了
.on('load', function () {
instead
反而
.each(function(){
used in this answerit helps to eliminate the problem with empty values ??of height and width when the picture is not yet loaded
在这个答案中使用它有助于消除图片尚未加载时高度和宽度为空值的问题
<style type="text/css">
.fixed-div {
position: relative;
}
.variable {
width: 100%;
height: auto;
}
.variable.js-fix {
position:absolute;
top:50%;
left:50%;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
$(".fixed-div img.variable").on('load', 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.
console.log("width", $(this).width());
console.log("height", $(this).height());
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
hTall = '-' + hTall + 'px';
$(this).addClass("js-fix").css({
"margin-left" : hWide,
"margin-top" : hTall
});
});
});
</script>
<div class="fixed-div">
<img class="variable" src=""/>
</div>
回答by Dhwani sanghvi
Center image horizontally and vertically
水平和垂直居中图像
DEMO:
演示:
http://jsfiddle.net/DhwaniSanghvi/9jxzqu6j/
http://jsfiddle.net/DhwaniSanghvi/9jxzqu6j/
.section {
background: black;
color: white;
border-radius: 1em;
padding: 1em;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}

