HTML/CSS 在段落和无序列表旁边 float 一个 img

标签 html css css-float

我在这里看到过类似的问题,但给出的解决方案都没有帮助我。
我试图在

    和另一个


    的分组旁边 float 一个 这是标签的样子

    <p></p>
    <ul>
        <li></li>
        <li></li>
    </ul>
    <p></p>
    <img src="" alt="" />
    

    所以我所需要的只是让 位于所有其他三个标签的旁边。
    我想我缺少一个非常明显的解决方案。

最佳答案

无论您尝试将图像向右还是向左浮动,当前的 2 个答案都不会将图像放在文本旁边 - 它们只会将图像向右下方 float 文本。

当您 float 图像时的示例 - 它不起作用:)

img { 
    float:right;
    /* styling to show a "placeholder" for the image so you can see where it would appear */
    width:100px; height:100px; background:#ccc; 
}
<p>paragraph</p>
    <ul>
        <li>list item</li>
        <li>list item</li>
    </ul>
    <p>paragraph</p>
<img src="" alt="" class="" />

有 2 种方法可以做到这一点,具体取决于您是否可以控制 HTML。

  1. 将图片移动到文字之前,然后 float

如果可以更改 html,则需要将图像移动到文本之前,以便文本可以填充图像 float 后剩余的空间,例如

img { 
    float:right;
    /* styling to show a "placeholder" for the image so you can see where it would appear */
    width:100px; height:100px; background:#ccc; 
}
<img src="" alt="" />
<p>paragraph</p>
    <ul>
        <li>list item</li>
        <li>list item</li>
    </ul>
    <p>paragraph</p>

  1. 将文本向左浮动,将图像向右浮动

img { 
    float:right;
    /* styling to show a "placeholder" for the image so you can see where it would appear */
    width:100px; height:100px; background:#ccc; 
}

.text { float:left;}
<div class="text">
    <p>paragraph</p>
    <ul>
        <li>list item</li>
        <li>list item</li>
    </ul>
    <p>paragraph</p>
</div>
<img  style="float: right" alt="" />

但是请注意,这会导致更多问题,因为当您 float 元素时,会将它们从流中移除,并且将两者都从流中移除会变得更加复杂。

使用 Clearfix

一种选择是使用 clearfix 使 float 后的内容“清除”它们 - 请参阅此代码段以了解使用和不使用 clearfix 时发生的情况的示例。

img { 
    float:right;
    /* styling to show a "placeholder" for the image so you can see where it would appear */
    width:100px; height:100px; background:#ccc; 
}

.text { float:left;}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

hr { clear:both;}
<h3>Without Clearfix</h3>
<div class="text">
    <p>paragraph</p>
    <ul>
        <li>list item</li>
        <li>list item</li>
    </ul>
    <p>paragraph</p>
</div>
<img style="float: right" alt="" />
<p><b>This is content after the floats</b></p>

<hr>

<h3>With Clearfix</h3>
<div class="clearfix">
<div class="text">
    <p>paragraph</p>
    <ul>
        <li>list item</li>
        <li>list item</li>
    </ul>
    <p>paragraph</p>
</div>
<img style="float: right" alt="" />
</div>
<p><b>This is content after the floats</b></p>

关于HTML/CSS 在段落和无序列表旁边 float 一个 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46918376/

相关文章:

javascript - 在同一个类中添加值并返回总和

javascript - Firefox 删除了我的 float :left

css - 清除修复的问题不适用于 960 网格系统

javascript - 使用 Ajax/Jquery 显示此页面的任何内容到另一个页面

html - 我的网站有一个静态子域,其中包含图像/css/js,每当我尝试将代码指向它时......没有任何效果

html - SVG 图标 - 严重垂直对齐

html - 如何在 CSS 和 HTML 中创建价格标签形状

html - div 底部的不透明背景未正确附加

html - 部分与 div 重叠

php - 使用 HTML PHP MySQL 的下拉导航菜单