0

An img with height: 100% applies a scroll bar to the web browser.

If there is no <!DOCTYPE> tag, there is no scroll bar. When you insert the <!DOCTYPE> tag, a scroll bar is created.

I tried several things, but I think <!DOCTYPE> is a problem

I would like to make the scroll bar disappear without using overflow.

<html>
    <head>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            html, body {
                width: 100%;
                height: 100%;
            }
            img {
                width: 100%;
                height: 100%;
            }
        </style>
    </head>
    <body>
        <img src="test.jpg">
    </body>
</html>

The above source code has no scroll bars, but inserting <!doctype html> creates a scroll bar.

I have used the developer tools to make sure the html, body, and img heights are the same.

I want to know why <!doctype html> causes scroll bars. And I want to know how to fix it without using overflow in CSS.

I have tried several codes: I have tried several source code

a stone arachnid
  • 1,272
  • 1
  • 15
  • 27
mp662002
  • 25
  • 1
  • 2

1 Answers1

2

Add display: block to <img>.

By default, <img> has display: inline as default display style. And inline and inline-block display style will apply a blank space between elements.

To remove the blank space, you can read these links:

  1. Display: Inline block - What is that space?
  2. https://css-tricks.com/fighting-the-space-between-inline-block-elements/

Alternatively, just make its display style to display: block.

Before

* {
  box-sizing: border-box;
}

html, body {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

img {
  width: 100%;
  height: 100%;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/c/c2/Sig07-006.jpg">

After:

* {
  box-sizing: border-box;
}

html, body {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

img {
  width: 100%;
  height: 100%;
  
  /* ADD THIS */
  display: block;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/c/c2/Sig07-006.jpg">

As to why declaring <!DOCTYPE html> affects the layout, you can read this MDN doc.

Basically, without <!DOCTYPE html>, the browser will render the page with older render mode to support old web pages.

yqlim
  • 6,898
  • 3
  • 19
  • 43