首页 > 解决方案 > 浮动图像超出部分

问题描述

我正在尝试将 img 和 text 对齐到一个图像向左浮动而文本向右浮动的位置。我试图达到的 在此处输入图像描述 结果:这是我的结果: 在此处输入图像描述 正如你所看到的,我的图像由于某种原因超出了部分

我当前的代码:

 #intromessage {
        border: 1px solid #cccccc;
        text-align: right;
    }

    img {
        float: left;
        width: 50%;
        border: 1px solid #cccccc;
    }
<section id="intromessage">
            <h2>WELCOME TO BOOTWORLD</h2>
            <p>
                BootWorld is the largest online footwear retailer in the UK. <span> Our shop </span>always has stock of the latest designer footwear
                at the most competitive prices. Want to know more about us or our products, why not 
                <span>send us a message.</span>
            </p>
            <img alt="shoes" src="images/boots.png">
        </section>

标签: htmlcss

解决方案


在父元素上使用并将and标记display:flex;包装在一个 div 中,以便父元素中的两个子 div 显示为一个 flex 行。该元素将具有显示 flex 和ash2pid='cont'flex-directioncolumn


编辑: *正如这个问题的编辑所指出的,这个问题以最纯粹的形式确实有一个答案,我将为将来查看这个答案的人提供这个答案......

OP 遇到的问题是他们float在他们的 img 元素上使用了 a 。如果不清除浮动,他们的图像并没有像他们预期的那样向左浮动,而是显示在它应该浮动到左侧的同级文本内容下方。具有样式的图像float: left;在 div 内intromessage,但在页面上它位于该容器 div 之外。浮动对象不会增加它们所在对象的高度。问题是没有clear:调用浮动。为了解决这个问题,我们添加一个空div元素并clear: left在左浮动 div 或clear: right右浮动 div 上设置样式,或者如果clear: both想清除左右浮动。

<div style="clear: both;"></div>

来自 MDN的重要提示:clear CSS 属性设置是否必须将元素移动到(清除)它之前的浮动元素之下。

处理此问题的一种更现代的方法是使用gridor flex,请参见下面的代码段:

#intromessage {
  display: flex;
  border: 1px solid #cccccc;
}

#cont {
  padding: 5px;
  display: flex;
  flex-direction: column;
}

h2{
  font-size: 1rem;
}

img {
  width: 50%;
  border: 1px solid #cccccc;
  padding: 5px;
}
<section id="intromessage">
  <img alt="shoes" src="https://cdn11.bigcommerce.com/s-h8hjw/products/927/images/735/WBHQ19-Retail-Product-OnWhite-Boots-M-1500x1425__00368.1599677007.475.500.png?c=2">
  <div id="cont">

    <h2>WELCOME TO BOOTWORLD</h2>
    <p>
      BootWorld is the largest online footwear retailer in the UK. <span> Our shop </span>always has stock of the latest designer footwear at the most competitive prices. Want to know more about us or our products, why not
      <span>send us a message.</span>
    </p>
  </div>

</section>


推荐阅读