为页面添加边距,包括绝对/固定定位元素

问题描述 投票:1回答:2

有没有办法为页面设置全局页边距,包括绝对和固定定位元素?

javascript html css
2个回答
3
投票

这可能是您使用在其上设置了变换的元素包装这些绝对/固定元素。

看一下规格:The Transform Rendering Model

为'transform'属性指定“none”以外的值会在应用它的元素处建立新的局部坐标系。

body {
  margin: 100px;
  color: white;
  transform: translateX(0);
  border-top: 2px solid green;
}
.absolute, .fixed {
  width: 100px;
  height: 100px;
  top: 0; 
}
.absolute {
  position: absolute;
  background-color: red;
  left: 0;
}
.fixed {
  position: fixed;
  background-color: blue;
  right: 0;
}
<div class="absolute">absolute</div>
<div class="fixed">fixed</div>

请注意,在上面的代码片段中,绝对元素和固定元素都是相对于具有边距的主体定位的。

注意:

1)我不一定建议以这种方式使用它,因为从长远来看它很可能会造成混乱。

2)正如@Temani Afif指出的那样,固定元素将以这种方式表现得像绝对元素 - 因此根据上下文,这种技术可能无法正常工作。


-1
投票

您可以使用通配符选择器为所有元素添加边距,但是您将花费大量时间在内部元素上取消它。您可以尝试使用body> *来为顶级元素添加边距。

body > * {
  margin: 50px;
}

#abs {
  position: absolute;
  top: 0;
  left: 0;
  background: red;
  width: 100px;
  height: 100px;
}

#abs .inner {
  position: absolute;
  top: 0;
  left: 0;
  background: blue;
  width: 50px;
  height: 50px;
}

#fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  background: green;
  width: 100px;
  height: 100px;
}
<div id="fixed"></div>
<div id="abs">
  <div class="inner"></div>
<div>
© www.soinside.com 2019 - 2024. All rights reserved.