-->

Text wraps around floating div but borders and

2019-02-12 02:28发布

问题:

I have a div that is float: right and it is inside a parent div. There are p elements inside that same parent div also, and the text wraps around the float: right div properly. However, if I set the p elements to have a border, or do a <hr />, the border does not stop where the text stops, but extends behind the float: right div.

Here is a beautiful mspaint depiction of the situation:

Note that the green part of the black horizontal line is behind the floating div.

How do I get the border or <hr /> or whatever to be only as wide as the text, and not go behind the div?

回答1:

I know this problem was posted some time ago, but I had the same problem today and found another solution:

http://jsfiddle.net/MvX62/

I use border-bottom instead of the <hr /> tag and had to add an overflow: hidden;. Look at the fiddle, i think this is more useful then the accepted solution, because you can also add a margin to the horizontal line and there is the same gap, as the text has.

Also you don't need to define z values and don't need any hacks or workarounds.



回答2:

I've had this problem before, and I wasn't sure if it was solvable.

In your case, however, you could wrap the green box with another element and swap margin with padding and set its background to #fff to cover the offending line.



回答3:

Check out the fiddle...

http://jsfiddle.net/UnsungHero97/8BwGB/3/

What I did here was give the floated element a z-index CSS property, which will put it "above" the non floated element (which has a smaller valued z-index) and the <hr /> will not go above the floated element.

In regards to getting it as wide as the text, in my example it is as wide as the text, but I'm not sure if that holds across browsers (I'm on Chrome). Let me know if it doesn't.

I hope this helps.
Hristo

p.s. excellent mspaint skillz :)



回答4:

You would have to set the width of the paragraphs to the width of the container minus the width of the floating element, or you could give them a margin on the same side of the float equal to the float's width.



回答5:

Div cannot wrap around another div. Wrapping is text-only property. You can simulate wrapping by setting the margin-right for the master div to the width of the div you want it to wrap, but text wil not flow under the inset div.