请给我一些空间

Avatar of Geoff Graham
Geoff Graham

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

有很多方法可以做到这一点。当然,有些方法更明智,更适合某些情况。

我们可以在 HTML 中直接实现

<p>We go from one line...<br><br> down a couple more.</p>

但 CSS 的真正用途就在于此

<p>We go from one line...<span>down a couple more.</span></p>
span {
  display: block;
  margin-block-start: 1.5rem;
}

行高也可以在文本行之间提供额外的呼吸空间

p {
  line-height: 1.35;
}

既然我们正在讨论文本,还有 letter-spacingword-spacing,更不用说 text-indent

但让我们谈谈盒子而不是文本。假设我们有两个简单的 div

<div>Twiddle Dee</div>
<div>Twiddle Dum</div>

它们是块级元素,因此它们已经在不同的行上。我们可以再次使用 margin。或者我们可以使用 padding 来创建空间的印象。我想我们可以向任何方向 translate 这些元素

div:nth-child(2) {
  transform: translateY(100px);
}

但也许这些元素是 绝对定位 的,因此我们可以使用物理偏移量

div {
  position: absolute;
}
div:nth-child(1) {
  inset: 0;
}
div:nth-child(2) {
  inset-inline-start: 100px; /* or top: 100px; */
}

如果我们在网格容器中工作,那么我们就可以使用 gap

<section>
  <div>Twiddle Dee</div>
  <div>Twiddle Dum</div>
</section>
section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 100px;
}

同样的道理适用于弹性容器

section {
  display: flex;
  gap: 100px;
}

当我们在网格和弹性容器中工作时,我们可以调用任何对齐属性来生成空间。

section {
  display: flex;
  align-items: space-between;
  justify-content: space-between;
}

当然还有表格

<table cellspacing="100">
  <!-- etc.  -->
  <tbody>
    <tr>
      <td>Twiddle Dee</td>
      <td>Twiddle Dum</td>
    </tr>
  </tbody>
</table>

或者 CSS 方法

/* We could use `display: table` if we're not working in a table element. */
table {
  border-spacing: 100px;
}

让我们深入探讨一下偏远领域。我们可以使用具有硬颜色停止的线性渐变使一个元素看起来像两个元素

div {
  background-image:
    linear-gradient(
      to right,
      rgb(255 105 0 / 1) 50%,
      rgb(207 46 46 / 1) 50%,
      rgb(207 46 46 / 1) 100%
    );
}

然后我们做一个假动作,在两种颜色之间插入一个硬透明颜色停止

既然我们在这里做假动作,不妨加上老式的“透明”边框技巧

让我们再回到文本上。也许我们正在浮动一个元素,并希望文本围绕它环绕……以浮动元素的形状环绕,同时在两者之间留出一些空间。我们有 shape-margin 用于此

我敢提一下 spacer.gif 时代 吗?

<div>Twiddle Dee</div>
<img src="spacer.gif"> <!-- 🤢 -->
<div>Twiddle Dum</div>

一定还有更多

你们都是一群聪明人,有很多好主意。尽管来吧!