I've set up a JSFiddle to test several different solutions to this problem. Based on the [vague] criteria of
1) Maximum flexibility
2) No weird behavior
The accepted answer here of
img { display: block; }
which is recommended by a lot of people (such as in this excellent article), actually ranks fourth.
1st, 2nd, and 3rd place are all a toss-up between these three solutions:
1) The solution given by @Dave Kok and @Hasan Gursoy:
img { vertical-align: top; } /* or bottom */
pros:
- All display values work on both the parent and img.
- No very strange behavior; any siblings of the img fall where you'd expect them to.
- Very efficient.
cons:
- In the [perfectly valid] case of both the parent and img having `display: inline`, the value of this property can determine the position of the img's parent (a bit strange).
2) Setting font-size: 0;
on the parent element:
.parent {
font-size: 0;
vertical-align: top;
}
.parent > * {
font-size: 16px;
vertical-align: top;
}
Since this one [kind of] requires vertical-align: top
on the img
, this is basically an extension of the 1st solution.
pros:
- All display values work on both the parent and img.
- No very strange behavior; any siblings of the img fall where you'd expect them to.
- Fixes the inline whitespace problem for any siblings of the img.
- Although this still moves the position of the parent in the case of the parent and img both having `display: inline`, at least you can't see the parent anymore.
cons:
- Less efficient code.
- This assumes "correct" markup; if the img has text node siblings, they won't show up.
3) Setting line-height: 0
on the parent element:
.parent {
line-height: 0;
vertical-align: top;
}
.parent > * {
line-height: 1.15;
vertical-align: top;
}
Similar to the 2nd solution in that, to make it fully flexible, it basically becomes an extension of the 1st.
pros:
- Behaves like the first two solutions on all display combinations except when the parent and img have `display: inline`.
cons:
- Less efficient code.
- In the case of both the parent and img having `display: inline`, we get all sorts of crazy. (Maybe playing with the `line-height` property isn't the best idea...)
So there you have it. I hope this helps some poor soul.