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

Sass实现div内h3单独一行、p与button同行的布局方法

实现目标布局的两种Sass方案

根据你的需求,要让h3独占一行,p与button同行显示,这里提供两种可行的Sass实现方案:

方案1:不修改现有HTML结构(使用Grid布局)

Grid布局可以在不调整DOM结构的前提下,快速实现行列划分:

.nameHeader {
  width: 100%;
  height: 100%;
  padding: 1rem;
  // 定义网格:2列(第一列占满剩余空间,第二列自适应内容),2行(高度自适应内容)
  display: grid;
  grid-template-columns: 1fr auto;
  grid-template-rows: auto auto;
  gap: 0.8rem; // 控制行与行之间的间距

  h3 {
    font-weight: 600;
    grid-column: 1 / -1; // 让h3横跨所有列,独占一行
  }

  p {
    font-size: 20px;
    align-self: center; // 与button垂直居中对齐
  }

  &__icon {
    color: #ccc;
    align-self: center;
    background: transparent;
    border: none;
    cursor: pointer;
  }
}

方案2:调整HTML结构(使用Flex布局,更易维护)

如果允许微调DOM结构,将p和button放入一个容器中,用Flex实现同行布局会更直观:

修改后的HTML

<div className="nameHeader">
  <h3>{names}</h3>
  <div className="nameHeader__row">
    <p>{date}</p>
    <button
      className="nameHeader__icon"
      onClick={deletetNames}
    >
      <GrTrash />
    </button>
  </div>
</div>

对应的Sass代码

.nameHeader {
  width: 100%;
  height: 100%;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.8rem;

  h3 {
    font-weight: 600;
    // h3默认是块级元素,在flex column布局下自动独占一行
  }

  &__row {
    display: flex;
    justify-content: space-between; // 让p左对齐,button右对齐
    align-items: center; // 垂直居中对齐
  }

  p {
    font-size: 20px;
  }

  &__icon {
    color: #ccc;
    background: transparent;
    border: none;
    cursor: pointer;
  }
}

补充说明

  • 两种方案都能实现你要的效果,方案1适合不想改动DOM的场景,方案2的结构更清晰,后续扩展样式更方便。
  • 可以根据需求调整gap、justify-content等属性,控制元素间的间距和对齐方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:05:27