How To Center A Span Containing An Image In A Div
I have a main div (#homeGallery), in which i have a span(.imgClass) that is used to load one of a list of images. I need the image to be centered not only vertically but horizonta
Solution 1:
This is a jewel I found recently. Use position: absolute with a top, left, bottom and right. You can center your span horizontally and vertically.
HTML:
<div class="wrapper">
<span class="image"></span>
</div>
CSS:
.wrapper {
width:400px;
height: 400px;
position: relative;
background-color: #afafaf;
}
.wrapper .image {
position: absolute;
top: 25%;
left: 25%;
right: 25%;
bottom: 25%;
background-color: #000;
}
Solution 2:
You can try this code:-
#homeGallery > .imgClass > img {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
max-width:100%;
max-height:100%;
overflow:auto;
}
Solution 3:
You can try the following:
#homeGallery > .imgClass > img {
margin:0px auto;
display:block;
max-width:60%;
max-height:99%;
border: 2px solid;
}
Solution 4:
Here's a Fiddle
#homeGallery .imgClass {
position: relative;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
If you dont know the image width & height than you could use jQuery solution
$(function() {
var imgW = $('.imgClass').outerWidth(),
imgH = $('.imgClass').outerHeight();
$('.imgClass').css({ marginLeft: - imgW / 2 + 'px', marginTop: - imgH / 2 + 'px' });
});
and this CSS
#homeGallery .imgClass {
position: relative;
top: 50%;
left: 50%;
}
Solution 5:
This is my prefered method:
HTML
<div id="homeGallery">
<span class="imgClass">
<span class="fakeImg">You can use whatever img you want here</span>
</span>
</div>
CSS
#homeGallery{
height: 400px;
border: 1px solid #333;
text-align: center;
}
#homeGallery:before{
content: '';
height: 100%;
vertical-align: middle;
display: inline-block;
}
.imgClass{
display: inline-block;
vertical-align: middle;
text-align: left;
background-color: blue;
}
jsfiddle here.
The good side is that this is 100% css-based vertical alignment. You don't have to worry about screen size or DOM size change.
The cons is that it doesn't work on IE7 or lower.
Post a Comment for "How To Center A Span Containing An Image In A Div"