:before :after 伪元素的位置

Position of :before :after psuedo elements

  1. 有没有办法让伪元素:after服从我容器的宽度,所以它是橙色结束的地方(500px之后),或者:after 总是在元素内容结束的地方开始?

  2. 难道我元素的marginand/orpadding,总是会影响:before:after伪元素?我以为他们有自己的边距和填充。至少能够向我的元素添加填充不应该影响伪元素应该....

请参阅以下代码笔:http://codepen.io/anon/pen/wgaYZg

#container {
  width: 500px;
  background-color: orange;
  display: inline-block;
  padding: 50px;
  margin: 50px;
}
#container:before {
  background-color: grey;
  content: "before";
  width: 100px;
  display: inline-block;
}
#container:after {
  background-color: grey;
  content: "after";
  width: 100px;
  display: inline-block;
}
<div id="container">hello world</div>

这就是我想要做的事情:

要理解伪元素:before:after,就把它们看成是<span>标签的限定版,因为据我所知,伪元素只能包含图片或纯文本知道。默认情况下,它们没有自己的 paddingmargin

<container><:before>normal content<:after></container>

为了实现您的布局,我建议使用位置技巧而不引入任何新标签。

#container {
  background-color: orange;
  position: relative;
  width: 500px;
  padding: 50px 100px;
  box-sizing: border-box;
}
#container:before,
#container:after {
  position: absolute;
  top: 0;
  bottom: 0;
}
#container:before {
  background-color: grey;
  content: "before";
  width: 100px;
  left: 0;
}
#container:after {
  background-color: grey;
  content: "after";
  width: 100px;
  right: 0;
}
<div id="container">hello world</div>

否则,如果您可以将纯文本包装到 HTML 标签中,使用 flexbox 就很容易做到。

#container {
  width: 500px;
  background-color: orange;
  display: flex;
}
#container span {
  padding: 50px;
  flex: 1;
}
#container:before {
  background-color: grey;
  content: "before";
  width: 100px;
}
#container:after {
  background-color: grey;
  content: "after";
  width: 100px;
}
<div id="container"><span>hello world</span></div>