MultiDev
MultiDev

Reputation: 10649

How to center align img wrapped in SPAN tag?

I am trying to center align an image that is wrapped in a <span>, but I am having trouble doing so. I have uploaded my CSS and HTML to jsfiddle: http://jsfiddle.net/7nHhu/1/

I am trying to get the image to center align itself with the content in a "block" style (ie. all text above and below it, not wrapped to the left or right)

Any help would be greatly appreciated.

.imgframe {
border: 1px solid #EAEAEA;
display: inline-block;
margin: 8px;
}
.imgframe img {
border: 1px solid #FFFFFF;
margin: 0;
background: #F6F6F6;
padding: 8px;
-moz-box-shadow: 2px 2px 5px #CCCCCC;
-webkit-box-shadow: 2px 2px 5px #CCCCCC;
}

<span class="imgframe centerimg"><img src="http://i48.tinypic.com/31368e9.jpg" /></span>​

Upvotes: 4

Views: 42061

Answers (5)

uyghurbeg
uyghurbeg

Reputation: 310

span {position: absolute; top:0; left: 0; width: 100%; text-align: center;}
img {width:yourimagewidth; heigth: width:yourimageheigth}

Upvotes: -1

Foreever
Foreever

Reputation: 7468

I think it's more appropriate to use text-align for centering text rather than images. You could center an image by setting left and right margin auto.

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: auto;
    padding-top: 10px; //margin-top doesn't work
} 

Demo

Upvotes: 7

David Thomas
David Thomas

Reputation: 253318

Given your requirements, to keep the .imgframe element in-line, to avoid it taking up the full width of the enclosing element, and working without adding wrapping elements to your mark-up, the following works:

body {
    text-align: center;
}

body p {
    text-align: left;
}

JS Fiddle demo.

This would, probably, be less intrusive if you had the elements from your Fiddle wrapped in a specific, target-able, element; rather than the body, as the method, above, requires you to reset the text-align for all elements contained within the body. So, personally, I'd use:

<div id="contentWrapper">
    <p>...</p>
    <span class="imgframe">
        <img src="..." />
    </span>
    <p>...</p>
</div>

And:

#contentWrapper {
    text-align: center;
}

#contentWrapper p {
    text-align: left;
}

Just in order to minimise the amount of work required to tidy up afterwards.

Upvotes: 0

Musa
Musa

Reputation: 97672

Just make image wrapper block level element and text-align:center; it.

FIDDLE

or wrap it in another element if needed;

FIDDLE

Upvotes: 3

TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

In .imgframe, add width: 100%;

Upvotes: 0

Related Questions