2017-06-23 93 views
1

下面是我对伪元素忽略填充的解决方案,但它感觉有点“哈克”,因为我在伪元素上使用了负余量。如何在伪元素之前忽略元素填充?

此解决方案是否正常?

我也尝试使用left: 0; top: 0;,但后来我得到了我的伪元素相对于页面的主体,而不是元素。为什么?

CSS:

.block-header { 
    background-color: #3A658B; 
    height: 30px; 
    width: 100%; 
    line-height: 30px; 
    color: white; 
    font-size: 18px; 
    border-radius: 3px; 
    padding-left: 10px; 
} 
.block-header::before { 
    content: ''; 
    position: absolute; 
    margin-left: -10px; 
    height: 30px; 
    width: 10px; 
    background-color: #1E3552; 
    border-radius: 3px 0px 0px 3px; 
} 

回答

2

使用left: 0是罚款。这是正确的方法。

除了您没有在.block-header元素上指定position: relative

考虑一下:

  • 伪元素被认为是它的DOM元素的一个孩子。
  • 一个绝对定位的元素相对于其最近的定位祖先进行定位。
  • 当没有定位的祖先时,abspos元素相对于初始容器(即,HTML元素/视口)被定位。

.block-header { 
 
    background-color: #3A658B; 
 
    height: 30px; 
 
    line-height: 30px; 
 
    color: white; 
 
    font-size: 18px; 
 
    border-radius: 3px; 
 
    padding-left: 10px; 
 
    position: relative;  /* NEW */ 
 
} 
 

 
.block-header::before { 
 
    left: 0;     /* NEW */ 
 
    content: ''; 
 
    position: absolute; 
 
    height: 30px; 
 
    width: 10px; 
 
    background-color: #1E3552; 
 
    border-radius: 3px 0px 0px 3px; 
 
}
<div class="block-header">test</div>

更多信息请参见MDN