问题
Probably easiest to explain what I'm after with an image:

When I float an image the text runs around it which is great. BUT, depending on the amount of text and the image size, I'm often left with these awkward bits. In this case the awkward text would look better in the column next to the image.
I could add more bottom margin to the image depending on how much awkward text there is BUT in a responsive design the image shrinks and the text stays the same size so there is no way of doing this for every image at every break point.
I could use "overflow:auto" on all paragraphs so that it creates a new layout context and stops the text from wrapping altogether. BUT I want the text to float when there is enough text and again I don't get control over the final output.
I have a feeling that unless there's some overly complicated JS that can run on this (and can handle the screen size changing on a responsive site) there is no solution. So my question would be how do people handle this? Ignore it? Use JS?
Thanks
回答1:
I don't think you can do this in CSS. However, I don't think the JavaScript would be overly complicated either. I'd recommend using element.getClientRects(), which returns a list of TextRectangle objects. For inline elements, each TextRectangle object represents a line of text.
If you check that the left offset of the last TextRectangle is different to the left offset of the penultimate TextRectangle, you know that the last line is a "straggler" and can adjust the image's bottom margin by the height of one TextRectangle (bottom - top
).
getClientRects
was standardised in CSSOM, but may have buggy implementations in some browsers.
From a more personal point of view, I'd say that I think it looks fine the way it is and I probably wouldn't worry about it if I were you.
回答2:
The easiest fix for this is to add another DIV around your text and float that left as well.
So your html would end up like:
<div>
<img src="">
<div>
My text...
</div>
</div>
来源:https://stackoverflow.com/questions/14811049/awkward-line-wrap-around-image