【问题标题】:How to set different margin-top for span elements? [duplicate]如何为 span 元素设置不同的 margin-top? [复制]
【发布时间】:2020-01-24 23:22:39
【问题描述】:

我想为 span 元素设置不同的边距。例如,margin-top: 25px 应该是第一个 span 元素,margin-top: 15px 应该是第二个元素:

    <div style="background: green">
       <span style="display: inline-block; margin-top: 25px;">1</span>
       <span style="display: inline-block; margin-top: 15px;">2</span>
    </div>

但是,第二个spanmargin-top: 25px

是否可以为两个span 元素设置不同的margin-top

【问题讨论】:

  • 是什么让你认为他们现在没有这个?
  • 他们都站在同一个基线上,你可以重置垂直对齐或使用浮动或弹性
  • @G-Cyr 你能用flex显示代码吗?
  • 只需将 display:flex 添加到父级(绿色背景)。有用的链接css-tricks.com/snippets/css/a-guide-to-flexbox
  • @G-Cyr 非常感谢您!:) 它有效!我真的很惭愧!点赞!

标签: html css


【解决方案1】:

您需要输入vertical-align: top。默认情况下,inline-block 元素将下沉到其兄弟元素的级别。

【讨论】:

  • 非常感谢!有用!我会将你的回复标记为答案
【解决方案2】:

只是为了表明他们确实有我添加了一个边框并在容器上放置了一个弹性显示。这也取决于您在视觉上想要的方式。我添加了第二个示例,它在不更改边框包含大小的情况下移动。

.thing {
  display: flex;
  background: green
}

.thing-span {
  display: inline-block;
  border: yellow 1px solid;
}

.thing-span.one {
  margin-top: 25px;
}

.thing-span.two {
  margin-top: 15px;
}
<div class="thing">
  <span class="thing-span one">1</span>
  <span class ="thing-span two">2</span>
</div>

另一种方式

.thing {
  
  background: green
}

.thing-span {
  display: inline-block;
  border: yellow 1px solid;
  vertical-align:top;
}

.thing-span.one {
  margin-top: 25px;
}

.thing-span.two {
  margin-top: 15px;
}
<div class="thing">
  <span class="thing-span one">1</span>
  <span class ="thing-span two">2</span>
</div>

【讨论】:

  • 如果父级是弹性盒子,则不需要内联块;)
  • @G-Cyr - 是的,但我想以视觉方式展示第二个示例 - 这可能会影响对如何完成此操作的选择。而且,这就是 OP 所拥有的,可能会产生其他影响。
  • 对于演示,您可以将 display:flex 设置为悬停,这样他就可以看到两种布局显示之间的区别;)
  • 做很多选择,所以时间很少:)
猜你喜欢
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 2017-09-16
  • 2014-02-23
  • 2013-03-01
相关资源
最近更新 更多