首页 > 解决方案 > Set equal vertical margins to any block element at once

问题描述

By default, most browsers will add a top and bottom margin of 1em to many block elements, like ol, ul, blockquote, h1, h2, etc.

Is there any short and clever selector that can change theses vertical margins (let say to 1.45em) all at once, without having to list every element in the CSS file?

Note: This question have been marked as a [duplicate.] But I am not trying to select all block elements by their properties (which I know is imposible in CSS), nor do I want to select all block elements by listing them one by one. I am concern in creating an equal vertical (top and bottom) margin in all elements that by default create a new line, by using the simplest selector posible.

标签: csscss-selectors

解决方案


到目前为止我发现的最好方法是使用通用选择器:

:root {
  --custom-vertical-margin: 1.5rem;
}

* {
  margin-top: var(--custom-vertical-margin);
  margin-bottom: var(--custom-vertical-margin);
}

尽管通用选择器也将定位内联元素,但它们不会也不会受到垂直边距的影响。

这完成了问题所在:一次在任何块元素上设置相等的垂直边距而不必在 CSS 文件中列出每个元素[with display:blockproperty],也不必尝试通过它们的属性来定位元素(这在 CSS 中是不可能的)。


推荐阅读