You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS实现:仅当h1为两行及以上时.by-line移至图片下方

动态调整.by-line位置的解决方案

我来帮你搞定这个布局需求!你想要实现的是:当h1内容只有一行时,.by-line留在蓝色图片右侧;当h1换行成两行及以上时,.by-line移到图片下方。下面是两种可行的方案,你可以根据实际场景选择:

方案1:纯CSS Flex布局(基于宽度阈值)

这个方案适合容器宽度固定的场景,我们通过调整布局结构,让h1和.by-line组成的容器在h1一行时与图片并排,当h1内容过长换行时,自动占据整行。

首先修改HTML结构,把h1和.by-line包裹进一个新容器:

<div class="container">
  <div class="img"></div>
  <div class="text-content">
    <h1>Blah blah blah blah blah</h1>
    <div class="by-line">
      <span class="author">By: <a>Company ABC Incorporated</a></span>
      <a class="reviews">1232 Reviews</a>
      <a class="write-full-review">Write a full review</a>
    </div>
  </div>
  <p><strong>54 People Recommend This Product</strong></p>
</div>

然后更新CSS:

.container {
  width: 300px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 可选,增加图片和文本的间距 */
}
.img {
  width: 15%;
  height: 100px;
  background: blue;
  flex-shrink: 0; /* 防止图片被压缩变形 */
}
.text-content {
  flex: 1;
  min-width: 0; /* 让文本容器可以收缩,避免内容溢出 */
}
h1 {
  margin-bottom: 0;
  word-wrap: break-word;
}
a {
  text-decoration: underline;
}
.by-line {
  background: yellow;
}

/* 当容器宽度小于阈值时,让文本容器占满整行(对应h1换行的情况) */
/* 阈值计算:容器宽度300px - 图片宽度15% = 255px,可根据实际情况调整 */
@media (max-width: 255px) {
  .text-content {
    width: 100%;
  }
}

方案2:JavaScript+CSS(精准匹配内容行数)

纯CSS没法直接检测元素内容的行数,所以用JS可以精准判断h1是否换行,然后动态调整.by-line的位置,适配所有场景,包括窗口大小变化。

首先添加一个额外的CSS类:

.by-line.full-width {
  clear: left;
  width: 100%;
  margin-top: 8px; /* 可选,增加和图片的间距 */
}

然后添加JavaScript代码:

function adjustByLinePosition() {
  const h1 = document.querySelector('h1');
  const byLine = document.querySelector('.by-line');
  // 获取h1单行文本的高度
  const singleLineHeight = parseFloat(getComputedStyle(h1).lineHeight);
  // 获取h1的实际高度
  const actualHeight = h1.offsetHeight;
  
  // 判断h1是否换行
  if (actualHeight > singleLineHeight) {
    byLine.classList.add('full-width');
  } else {
    byLine.classList.remove('full-width');
  }
}

// 页面加载时执行一次检测
window.addEventListener('load', adjustByLinePosition);
// 窗口大小变化时重新检测
window.addEventListener('resize', adjustByLinePosition);

方案对比

  • 方案1纯CSS实现,代码简洁,但依赖容器宽度阈值,适合固定宽度的场景;
  • 方案2精准匹配h1的行数变化,适配各种情况,包括动态内容和窗口缩放,灵活性更高。

内容的提问来源于stack exchange,提问作者learningtech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:02:47