温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - position a div anywhere on the page but still have text wrap around it
css html javascript

javascript - 将div放置在页面上的任何位置,但仍然有环绕文本

发布于 2020-03-28 23:22:31

我希望能够使用CSS将div放置在页面上的任何位置,但仍将文本换行。

到目前为止,我的代码:

.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>

除了在页面的顶角之外,我没有找到其他可以帮助我定位的内容,我需要将其定位在页面下方。

对我来说,一个依靠原始Javascript的解决方案是可以的。

我不能依靠在文本中创建一个中断来放置浮动元素,因为其中的内容可能会更改。

查看更多

查看更多

提问者
MindRobotics
被浏览
25
G-Cyrillus 2020-01-31 17:44

您需要使用另一个浮动元素并将其清除,以便文本可以一直沿浮动元素流到一边。

带有3.6em的伪示例(大约3行),将.float推到第四行级别。width:100%从您自己的代码保存在此演示中

.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>

如果不是要跨越整个宽度,请删除width:100%(请参阅像素值)

.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>