【问题标题】:How to set left and right CSS properties without setting top and bottom如何在不设置顶部和底部的情况下设置左右 CSS 属性
【发布时间】:2021-09-30 03:35:47
【问题描述】:

有什么方法可以将左右(边距、内边距、边框宽度等)设置为相同的值,而无需设置顶部和底部完全是一种表达方式,而不是...

.my-class-name { 
  margin-left: 2px; 
  margin-right: 2px;
}

对于属性,如果我希望左右为相同的值,而我的顶部和底部为其他值,我可以执行类似的操作

.my-class-name { margin: 3px 2px; }  

但要仅设置左右边距,我曾认为可能有一个类似于 unsetinherit 的关键字,它可能是一个“未指定”的设置,可能会让我做类似的事情

.my-class-name { margin: unspecified 2px; }

因此让其他早期的 CSS 占据同一个选择器。但似乎没有一个关键字可以做到这一点,除非我遗漏了一些东西。我也想知道如何在没有左或右的情况下进行上下移动。

那么有办法吗?或者你需要像 Sass 这样的 CSS 超集吗?

【问题讨论】:

  • margin: auto 30px;margin: 30px auto; 如果我理解正确的话你可以
  • autois not the same as "not specified"。我不想要auto
  • 我知道这已经被确认了......但是,出于好奇......为什么不只是“margin-top:x;”和“margin-bottom:x;”
  • 这不能回答问题,但 SASS 不起作用,因为它无论如何都会被编译为 CSS,而您仍然需要设置属性。您是否有不想使用auto 的原因?我正在阅读您链接到的 MDN 规范,它看起来 auto 将顶部和底部设置为 0,这恰好与 initial 相同。我意识到浏览器会解释 auto,但我猜 99.99% 的浏览器会将 auto 计算为 0。
  • @disinfor 自动将元素居中,如果你正在使用 flexbox 和 CSS 网格。它可以轻松破坏您的布局

标签: css


【解决方案1】:

是的,使用margin-inlinemargin-block

.box { 
  margin-inline: 10px; /* left and right */
  
  width:50px;
  height:50px;
  display:inline-block;
  background:red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

这些属性称为“流相关属性”,它们适用于填充、边框等:https://drafts.csswg.org/css-logical/

您不必担心支持,因为它非常好:https://caniuse.com/mdn-css_properties_margin-inline

相关:

What is the difference between margin-block-start and margin-top?

Is there a css function that allows me to set the values of top, right, bottom, and left for position all in one line?

【讨论】:

  • 啊,那是新的,所以这是我想做的一部分。看起来还有padding-inlinepadding-block,以及border-inline-widthborder-block-width。酷!
  • @PatrickSzalapski 以及边框、边框半径和替换宽度/高度的属性
  • @PatrickSzalapski border-inline-width
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 2019-12-14
  • 1970-01-01
相关资源
最近更新 更多