margin-top and position: sticky in Edge

Viewed 944

I'm trying to create a sticky header and noticed that in Edge the header's margin is doubled for some reason.

UPDATED Here is the URL on full page example https://codepen.io/galuka/full/qBZJOeJ

UPDATED 2 It looks like new Microsoft Edge based on Chromium works OK, so issue appears only on non-Chromium Edge versions.

Here is a simplified example of the issue:

.container {
  margin: 0 auto;
  width: 600px;
}
.sticky {
  margin-top: 80px;
  position: sticky;
  top: 0;
  background-color: orange;
  height: 100px;
}
<div class="container">
  <div class="sticky">
    Here goes sticky header
  </div>
  <div>
    Lorem ipsum dolor sit amet, ...
  </div>
 </div>

In Chrome and Firefox it works as expected, but in Edge the margin looks like 160px rather than 80px.

I also noticed that the issue can be fixed if I add any positive padding to the container class, for example 1px.

.container {
  margin: 0 auto;
  width: 600px;
  padding-top: 1px;
}
.sticky {
  margin-top: 80px;
  position: sticky;
  top: 0;
  background-color: orange;
  height: 100px;
}
<div class="container">
  <div class="sticky">
    Here goes sticky header
  </div>
  <div>
    Lorem ipsum dolor sit amet, ...
  </div>
 </div>

I'm quite new to CSS, so if anybody can explain this behaviour, I'd really appreciate it.

1 Answers

Browsers implement some default styles via a CSS file called User Agent Style Sheet. To ensure consistency across different browsers, you should add a small rule at the top of your CSS file. The code zeros out margins and padding ensuring consistency:

*{
    margin: 0;
    padding: 0;
}

As you stated that adding a padding solved the problem, this is definitely the solution. Furthermore you can right-click on any element on a webpage and choose inspect element and you would be able to see all the CSS applied to that element.

Related