CSS 使用 :before/:after 选择器在元素周围添加边距

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7479184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:39:46  来源:igfitidea点击:

Using :before/:after Selectors to add Margins Around Elements

csscss-selectorspseudo-element

提问by Dale Rollinson

I implemented (a modified version of) Gene Locklin's 'depth' which works just fine, here's the code:

我实现了(修改版)Gene Locklin 的“深度”,效果很好,代码如下:

body:before {
    height: 10px;
    width: 110%;
    position: fixed;
    top: -10px;
    left: -10px;
    z-index: 6;
    -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,0.8);
    -moz-box-shadow: 0px 0px 10px rgba(0,0,0,0.8);
    box-shadow: 0px 0px 10px rgba(0,0,0,0.8);
    content: "";
}

But I would like to use the :before & :after selectors to add margins or padding, you know some kind of gap, to separate a form from the surrounding text.

但我想使用 :before & :after 选择器来添加边距或填充,你知道某种间隙,将表单与周围的文本分开。

This comes after me trying to use these selectors to give some spacing around specific paragraphs, without success I turned to styling these on the basis of their target attributes.

这是在我尝试使用这些选择器在特定段落周围留出一些间距之后发生的,但没有成功,我转向根据它们的目标属性对它们进行样式设置。

I realize that the selectors were designed primarily to facilite auto-text and that it's perfectly easy to do this with margins or padding (added following queries below),line breaks, spans, an empty division, or even using JavaScript to create an element, and . But I would like to do this with :before & :after.

我意识到选择器主要是为了方便自动文本而设计的,使用边距或填充(在下面的查询中添加)、换行符、跨度、空分区,甚至使用 JavaScript 来创建元素,都非常容易做到这一点,和 。但我想用 :before & :after 来做到这一点。

Here's the example code that I would like to get working:

这是我想要开始工作的示例代码:

form:before {
    height: 20px;
    content: "";
}

form:after {
    height: 20px;
    content: "";
    }

Possibilities I think may be preventing this from working... :before/:after need to be displayed as block-level as they are normally inline (but the 'depth' doesn't need this?) and/or :before/:after require absolute positioning.

我认为可能会阻止它工作...... :before/:after 需要显示为块级,因为它们通常是内联的(但“深度”不需要这个?)和/或 :before/:后要求绝对定位。

Thank you in advance for your generous input.

预先感谢您的慷慨投入。

回答by Adam Eberlin

Try specifying display: block;. They don't need to be position: absolute;.

尝试指定display: block;. 他们不需要是position: absolute;

form:after {
  content: ' ';
  display: block;
  height: 20px;
}

form:before {
  content: ' ';
  display: block;
  height: 20px;
}