【问题标题】:CSS Layout of 2 columns with right column snapping down when it's width < 150px2列的CSS布局,当宽度<150px时右列向下对齐
【发布时间】:2020-10-07 23:40:40
【问题描述】:

我尝试了很多东西,但似乎无法格式化:

我需要一个最大宽度为 300 像素的外部容器,其中包含 2 列数据。左侧是图像(它的宽度可以变化)。右栏是文本。文本应该保留在它的列中,但如果它的列改变宽度(例如,当有更宽的图像或用户缩小屏幕时),则换行或扩展。当右列低于 150 像素时,我希望文本下降到图像下方并使用 100% 的外部容器(因此会有 2 行数据而不是 2 列。

例如:

如果图像不存在,我希望文本仅使用 100% 的外部容器。如果可能的话,我不想包含 javascript。这是我尝试过的。

.container {
  background-color: yellow;
  max-width:300px;
}

.container .item {
  display: inline-block;
  border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
</style>
</head>
<body>


<div class="container">
  <div class="item">my image</div>
  <div class="item">this is some text text text</div>
</div>

</body>
</html>

^^ 请注意,当您缩小屏幕时,文本根本不会在它的列中换行,而是将整个文本块捕捉到图像下方。我希望它包含在它自己的列中,然后仅当它的宽度低于 150 像素时才在下方捕捉。这可能吗?我希望我已经包含了足够的信息。

【问题讨论】:

  • 为什么投反对票?我真诚地寻求帮助?

标签: html css layout format


【解决方案1】:

flex-wrap:wrap;在容器上

flex:1 0 150px;在文字上,这翻译成

flex-grow:1;      // grow to fill remaining space
flex-shrink:0;    // don't ever shrink
flex-basis:150px; // have a minimum width of 150px

  1. 文本应保留在其列中,但在其列中换行或展开会更改宽度

flex-grow:1; 将使文本扩展以填充其列中的剩余空间,并在列更改宽度时换行。

  1. 当右栏小于 150 像素时,我希望文本位于图片下方

由于文本的最小宽度为150px,我们知道如果没有足够的空间,它至少需要150px 才能停留在图像旁边,这要归功于flex-wrap:wrap;父母。

  1. 并使用 100% 的外容器

再次flex-grow:1; 将使文本增长以填充剩余空间。

.container {
  background-color: yellow;
  max-width: 300px;
  display: flex;
  flex-wrap: wrap;
}

.container>div {
  flex: 1 0 150px;
}


/* Not needed */

.container {
  margin: 10px auto;
  overflow: auto;
  resize: horizontal;
}

p {
  display: table;
  margin: auto;
}
<div class="container">
  <img src="https://via.placeholder.com/100">
  <div>this is some text text text this is some text text text this is some text text text</div>
</div>
<p>The text column isn't below 150px so it stays</p>
<div class="container">
  <img src="https://via.placeholder.com/150">
  <div>this is some text text text this is some text text text this is some text text text</div>
</div>
<p>text column is below 150px so it drops below the img</p>
<div class="container">
  <img src="https://via.placeholder.com/250">
  <div>this is some text text text this is some text text text this is some text text text</div>
</div>

【讨论】:

  • 很好的答案!感谢您花时间看这个。这么简单的解决方案。我需要更好地使用 flexbox。这很有帮助。我希望我能奖励你一笔赏金,但这让我等了 2 天才能接受答案。
  • @RayLoveless 我很高兴能帮上忙:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 2021-05-31
  • 2013-07-14
  • 1970-01-01
相关资源
最近更新 更多