spiridon
spiridon

Reputation: 323

Adding a margin to a page, including absolutely/fixed positioned elements too

Is there a way to set a global margin to a page which will include absolutely and fixed positioned elements as well?

Upvotes: 1

Views: 54

Answers (2)

Danield
Danield

Reputation: 125493

This is possible is you wrap these absolute / fixed elements with an element which has transforms set on them.

Take a look at the spec: The Transform Rendering Model

Specifying a value other than ‘none’ for the ‘transform’ property establishes a new local coordinate system at the element that it is applied to.

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>

Notice that, in the above snippet, both the absolute and the fixed element are positioned relative to the body with the margin.

Note:

1) I don't necessarily recommend using it this way as it will most probably cause confusion in the long run.

2) As @Temani Afif pointed out fixed elements will behave like absolute elements this way - so this technique may not work as expected depending on the context.

Upvotes: 3

JasonB
JasonB

Reputation: 6368

You can add margin to all elements with the wildcard selector, but then you'll spend a lot of time cancelling this out on internal elements. You can try something like body > * to add margin to top level elements.

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>

Upvotes: -1

Related Questions