【问题标题】:Using ::after and ::before to go outside padding bounds使用 ::after 和 ::before 超出填充范围
【发布时间】:2020-02-01 22:25:55
【问题描述】:

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。

感谢您的帮助。

【问题讨论】:

  • 真的不清楚你在这里想要完成什么。能否请您更详细地解释一下这个问题?
  • 我认为p::before的声明不正确,属性和值应该用这个:而不是=分开

标签: html css layout padding


【解决方案1】:

您可以指定填充和边距,但通过考虑与负边距相同数量的填充然后依赖于一些背景颜色,使它们在视觉上为 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;
}
&lt;div class="box"&gt;TEXT HERE&lt;/div&gt;

如果你想用伪元素:

.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;
}
&lt;div class="box"&gt;TEXT HERE&lt;/div&gt;

【讨论】:

  • 根据提供的代码,我认为 OP 可能会从更多上下文中受益。单独的 CSS 对我们来说是不言自明的,但可能不是对所有人。
猜你喜欢
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2020-10-21
  • 2014-02-25
相关资源
最近更新 更多