首页 > 解决方案 > 使用 ::after 和 ::before 超出填充范围

问题描述

带有虚线背景的蓝色框内的文本,后面是较小的红色框并略微偏移

p {
  background: rgba(80,150,220,1);
  width: 100px;
  height: 100px;
  text-align:center;
}
p::before {
  content="asdf";
  background: rgba(220,150,80,1);
  width = 50px;
  height = 50px;
  top = - 25px;
  left = - 25px;
}
<!DOCTPE html>
<head>
</head>
<body>
    <p>TEXT HERE</p>
</body>

不改变 HTML

这是我的尝试。如果您有更好的解决方案,请告诉我。

应该显示虚线,它仅代表元素大小。

我试图将填充和边距保持为 0。

谢谢您的帮助。

标签: htmlcsslayoutpadding

解决方案


您可以指定填充和边距,但通过考虑与负边距相同的填充量,使它们在视觉上为 0,然后依赖于一些背景颜色:

.box {
  width: 100px;
  height: 100px;
  margin: -20px 0 0 -20px;
  padding: 20px 0 0  20px;
  background: 
    /* Top red line (width:80% height:20px) */
    linear-gradient(red,red) 0 0/80% 20px,
    /* left red line (width:20px height:80%)*/
    linear-gradient(red,red) 0 0/20px 80%,
    /* Main background; color only the content area (not the padding)*/
    rgba(80,150,220,1) content-box;
  background-repeat:no-repeat;
  
  text-align:center;
}
body {
 padding:50px;
}
<div class="box">TEXT HERE</div>

如果你想使用伪元素:

.box {
  width: 100px;
  height: 100px;
  text-align: center;
  background: rgba(80, 150, 220, 1);
  position: relative;
  z-index: 0;
}

.box:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: -20px;
  left: -20px;
  width: 80%;
  height: 80%;
  border-top: 20px solid red;
  border-left: 20px solid red;
}

body {
  padding: 50px;
}
<div class="box">TEXT HERE</div>


推荐阅读