Images are all different sizes. I'm using some jquery to resize them proportionally at 170px to fit inside the 180px #co-logo div. How can I get them to line up in the center of that #co-logo? I can't find a solution that works.
#co-logo
{
float: left;
width: 180px;
height: 180px;
margin: 20px 0 20px 20px;
background-color: White;
bor开发者_如何学JAVAder: 1px solid #d6d5d5;
text-align: center;
position: relative;
}
#co-logo img
{
position: absolute;
top: 50%;
left: 50%;
}
As you can see in your example, the images are positioned at the center (starting from the top left corner).
To make the center the way you desire, I suggest this solution: How to make an image center (vertically & horizontally) inside a bigger div
Since you're already using jQuery to manipulate the image's size, add their margin-top
and margin-left
programmatically (half for each).
EDIT:
(I don't know how you're placing the image size, you may need to change the height()
and width()
by $("#co-logo img").css('height')
and $("#co-logo img").css('width')
)
The javascript with jQuery to add the inline styles: simplified:
$("#co-logo img").css({'margin-top': -($("#co-logo img").height() / 2) + "px", 'margin-left': -($("#co-logo img").width() / 2) + "px"});
explained:
//get the image size:
var theHeight = $("#co-logo img").height();
var theWidth = $("#co-logo img").width();
//place them into the image styles:
$("#co-logo img").css({'margin-top': -theHeight / 2 + "px", 'margin-left': -theWidth / 2 + "px"});
EDIT 2:
Using each
to loop between every image.
Assuming you had the same ID for each block, you need to swap it with a class, like .co-logo
instead of #co-logo
(because IDs are unique), call the each like this:
$(".co-logo").each(function(){
$("img", $(this)).css({'margin-top': -($("img", $(this)).height() / 2) + "px", 'margin-left': -($("img", $(this)).width() / 2) + "px"});
});
That will do the trick!
#co-logo {
width: 180px;
height: 180px;
display: table-cell;
text-align: center;
vertical-align: middle;
margin: 20px 0 20px 20px;
background-color: White;
border: 1px solid #d6d5d5;
}
Don't Use float Left for this div
, if you want to apply float:left
for the div
use another div outside
精彩评论