Warm tip: This article is reproduced from stackoverflow.com, please click
css html javascript

position a div anywhere on the page but still have text wrap around it

发布于 2020-03-28 23:14:01

I want to be able to position a div anywhere on the page with CSS, but still have text wrap around it.

My code so far:

.float {
    position:relative;
    top:50px;
    float:right;
    background:rgba(255, 0, 0, 0.5);
    width:100%;
    display:block;
}
<div class="content">
    <div class="float">Stuff that should float</div>
    Other content to wrap around<br>
    More stuff to wrap around<br>
    Even more stuff to wrap around<br>
    And even more stuff to wrap around
</div>

I haven't found anything that can help me position this other than in the top corners of the page, and I need to position it a set amount down the page.

A solution that relies on vanilla Javascript is okay for me.

I can't rely on creating a break in the text to put the floating element because the content inside it might change.

Questioner
MindRobotics
Viewed
13
G-Cyrillus 2020-01-31 17:44

you need to use another floatting element and clear it from it, so the text can flow aside the floatting element all the way down.

example with a pseudo of 3.6em which is about 3 lines , pushing .float at the fourth line level. width:100% from your own code kept in this demo

.content:before {
  content: '';
  float: right;
  /*height:50px; pixel might not be the best unit here */
  height: 3.6em;/* about 3 lines (3 x 1.2em) Update to your needs*/
}

.float {
  clear: right;
  float: right;
  background: rgba(255, 0, 0, 0.5);
  width: 100%;
  display: block;
  /* float:right:width:100% ?? */
  /* do you need/mean : */text-align:right;/* ? */
}
<div class="content">
  <div class="float">Stuff that should float</div>
  Other content to wrap around<br> More stuff to wrap around<br> Even more stuff to wrap around<br> And even more stuff to wrap around
</div>

if it is not about spanning the whole width, remove width:100%. (see with a pixel value)

.content {
  width: 250px;/* shrink it for the demo*/
  border: solid;
}

.content:before {
  content: '';
  float: right;
  height: 50px;
}

.float {
  clear: right;
  float: right;
  background: rgba(255, 0, 0, 0.5);
}
<div class="content">
  <div class="float">Stuff that should float</div>
  Other content to wrap around<br> More stuff to wrap around<br> Even more stuff to wrap around<br> And even more stuff to wrap around
</div>