Search code examples
htmlcsswebresponsive-designtext-align

Header is being shifted when page is resized


I am making a website with a responsive design so that it still looks good and resizes well on different devices.

It all works well, apart from the h1 text. I have a container of fixed width 800px, that changes to a width of 100% at the appropriate screen size. The header text is centered, however, when the screen size changes and the container becomes 100% width, the header is now off-center, slightly shifted to the right.

Here is my HTML:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="styles.css">
        <title>Home</title>
    </head>
    <body>
        <div id="container">
            <h1>My Website!</h1>
        </div>
    </body>
</html>

And my CSS:

* {
    font-family: Helvetica Neue;
}

body {
    background-color: gray;
    margin: 0;
}

h1 {
    text-align: center;
}

#container {
    width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: white;
}

/* Resizability (Responsive Web Design) */

@media screen and (max-width: 840px) {

    #container {
        width: 100%;
    }

}

What is going wrong?


Solution

  • You could use something like this Fiddle.

    Add max-width: 100% and width: auto property like:

    CSS

    @media screen and (max-width: 840px) {
    
        #container {
            max-width: 100%;
            width: auto;
            border: 1px solid red; /*only for demonstration */
        }
    
    }