【问题标题】:CSS - Floating Two Divs Next To Eachother, Instead They Go Underneath EachotherCSS - 浮动两个相邻的 div,而不是它们在彼此下方
【发布时间】:2018-10-21 06:25:42
【问题描述】:

我正在尝试将两个 div 并排放置,并牢记移动访问者。

问题:当 div 中使用大量文本时,它不是并排浮动,而是在下方。

这是一个例子:

.codeblock {
     width:500px;
}
.left{
     float: left;
}
<div class="codeblock">
     <img src="https://placehold.it/307x322" class="left" style="width:125px">
     <div class="left">
           <h3>Some title</h3>
           <p>Some text with a long explanation of how buildings don't make the Earth any heavier because all the materials were already on it.</p>
     </div>
</div>

为什么会这样?有没有不使用固定值(不包括图片样式宽度)的解决方案?

【问题讨论】:

  • 图片的宽度总是一样吗?
  • css 浮动是用于内容流,而不是用于“定位”的东西

标签: html css css-float


【解决方案1】:

仅浮动图像

.codeblock {
     width:500px;
}
.left{
     float: left;
     margin-right:10px;
}
<div class="codeblock">
     <img src="https://placehold.it/307x322" class="left" style="width:125px">
     <div >
           <h3>Some title</h3>
           <p>Some text with a long explanation of how buildings don't make the Earth any heavier because all the materials were already on it.</p>
     </div>
</div>

【讨论】:

  • 记住你必须在内容之后清除浮动,或者将.codeblockoverflow属性设置为hidden
【解决方案2】:

另一种选择是使用 flexbox 代替浮动。这将是更多的工作,但它是一个新功能,尝试新事物总是好的。

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

更新

像这样:没有课。您通知主类它是 flexbox 并且它的子类将有一个填充将它们分开。

.codeblock {
  display: flex;
  width:500px;
}
.codeblock > * {
  padding: 0 10px;
}
<div class="codeblock">
     <img src="https://placehold.it/307x322">
     <div >
           <h3>Some title</h3>
           <p>Some text with a long explanation of how buildings don't make the Earth any heavier because all the materials were already on it.</p>
     </div>
</div>

【讨论】:

  • 同意。您指的是页面的哪一部分?
  • @AppelFlap 我已经用弹性框更新了评论。
【解决方案3】:

考虑到移动用户,我会使用 flex-wrap 和内容的最小值来这样做

.codeblock {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  max-width:500px;
}

.codeblock>img {
  flex: 0 0 125px;
  width: 125px;
  height: auto;
  margin-right: 20px;
}

.codeblock>div {
  flex: 1 1 200px;
  min-width: 200px;
}
<div class="codeblock">
  <img src="https://placehold.it/307x322">
  <div>
    <h3>Some title</h3>
    <p>Some text with a long explanation of how buildings don't make the Earth any heavier because all the materials were already on it.</p>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多