Anchor tag around fluid image in Internet Explorer 8
I'm having some trouble with a fluid layout (with images using max-width:100%) in Internet Explorer 8. The problem comes when I want to wrap an anchor tag around a flexible-width image and margins, padding, and borders get involved. This is a little harder than you'd think.
So the HTML is roughly this:
<div>
<a class="image-wrap" href="#">
<img alt="something" src="/path_to_image.jpg">
</a>
</div>
And the styling:
img {
max-width: 100%;
display: block;
}
.image-wrap {
padding: 5px;
border: 1px solid black;
display: block;
}
So what I have is a fluid image, surrounded by an anchor with a padding and border.
The above is good unless the image is smaller than the container. In that case, the anchor's padding and border expand beyond the image (filling the full width of the container).
So let's try something to force the anchor to fit its content:
.image-wrap {
padding: 5px;
border: 1px solid black;
display: inline-block;
}
OK, now the anchor box doesn't grow larger than the image, but the anchor tag is back to being not flexible in Firefox, Opera, and IE8+. But it does trigger layout in IE7 so that's taken care of. Next up:
.image开发者_如何转开发-wrap {
padding: 5px;
border: 1px solid black;
display: inline-block;
max-width: 100%;
}
Now the anchor is flexible again, but it's 12px larger than the container when the image starts scaling down. The anchor is calculating the width based on the image, then adding the border and padding. For some reason, Chrome and Safari don't do this. Anyway, alternate box model to the rescue:
.image-wrap {
padding: 5px;
border: 1px solid black;
display: inline-block;
max-width: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Now it's working as expected in Firefox, Chrome, Safari, Opera, IE7, IE9, but not IE8 for some reason. There, the anchor still extends outside the container. I'm a little stumped as to what to do, as box-sizing: border-box
is supposed to be supported in IE8.
I've got a JSFiddle page that isolates the issue http://jsfiddle.net/3gkXU/22/
As a last resort I could use JavaScript to detect if the anchor is bigger than its parent element, and then switch it to display: block
on the assumption that people are unlikely to resize their browser. I'm not against that, but is there a CSS solution here?
It appears that IE8 respects box-sizing: border-box
for width
, but not for max-width
. Solution: Forget about box-sizing
and insert an extra element.
jsFiddle: http://jsfiddle.net/wdKGU/1/
The new HTML:
<div>
<a class="image-wrap" href="#">
<span>
<img alt="something" src="/path_to_image.jpg">
</span>
</a>
</div>
The new styling:
img {
max-width: 100% !important;
display: block;
}
.image-wrap {
display: inline-block;
max-width: 100%;
}
.image-wrap span {
padding: 5px;
border: 1px solid black;
display: block;
}
精彩评论