user2901156
user2901156

Reputation: 67

What is causing two scrollbars here?

<!DOCTYPE html>
<html>
<head>
<style type="text/css">


.parent {
  height: 100vh;
  overflow: auto;
}

.first {
  height: 100vh;
}
.second {
  height: 100vh;
}
</style>
</head>
<body>


<div class="parent">
  <div class="first">
  <h1>haha</h1>
  </div>
  <div class="second">
  <h1>haha</h1>
  </div>
</div>


</body>
</html>

demo: http://codepen.io/anon/pen/zxKmyq

this code will give two scrollbars on the left.

However, if we change the code to

<!DOCTYPE html>
<html>
<head>
<style type="text/css">


* {   <!-- this is the only modification I made compared to the first code -->
    margin:0;     
    padding:0;   
}

.parent {
  height: 100vh;
  overflow: auto;
}

.first {
  height: 100vh;
}
.second {
  height: 100vh;
}
</style>
</head>
<body>


<div class="parent">
  <div class="first">
  <h1>haha</h1>
  </div>
  <div class="second">
  <h1>haha</h1>
  </div>
</div>


</body>
</html>

demo: http://codepen.io/anon/pen/gbwBQK

Then there will be only one scrollbar, which is desirable.

But I don't know how this works, i.e. why this simple modification will change the scrollbar.

Upvotes: 2

Views: 756

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241258

It's because most, if not all, browsers have a default margin of 8px on the body element.

When this default margin is present, the height of the browser is no longer 100%. Thus, a scrollbar is present.

More specifically, you are giving the .parent element a height of 100% of the browser. In addition to the 8px (top + bottom) margins, there is an excess of space.

100% + 16px != 100%.


In your second example, usage of

* {
    margin: 0;     
    padding: 0;   
}

..effectively removes this default margin.

You could merely use

body {
    margin: 0;
}

..for the same results.

Upvotes: 3

Related Questions