Search code examples
htmlcssaspect-ratio

How do i keep aspect ratio from changing?


So i have a background image and i have it set to be at width of 100% and height of 700px. It has attachment fixed cause im trying to make a parallax effect. The problem is that when i change the size of the browser, the picture loses its aspect ratio. So how do i keep it from changing, while keeping it responsive?

<header>
    <nav>
        <ul>
            <li id="back">
                <a href="#" id="back"><img src="../images2/back.png" /></a>
            </li>

            <li id="name">
                <h1>Person Name</h1>
            </li>
        </ul>
    </nav>
    <section id="iImage">

    </section>
</header>


#iImage{
width: 100%;
height: 700px;
background-image: url(../images2/DerekDesktop.jpg);
background-size:  100% 100%;
background-repeat: no-repeat;
background-attachment: fixed;
}

P.S. My next media query break point is at 1280px, so the background wont change until then. I also know that i am practicing some bad CSS but it is just a training website and wont be made public.


Solution

  • Change the background-size to cover instead of 100% 100%

    background-size: cover;
    

    EDIT- You set the width to 100% and height to 700px. So when you are resizing the window of the browser, it is basically maintaining the width and height and so breaking the aspect ratio of the image. So you have to compromise in one way. Remove the width or the height.

    You can also use background-position

    background-position: center;
    

    This code will align your image center.