Search code examples
htmlcssimageflexboxcentering

How to layout image so it is to left of ad space and yet centered using flexbox


I have the following HTML:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
      * {
        box-sizing: border-box;
      }

      section, header {
        width: 100vw;
        height: 100vh;
      }

      header {
        display: flex;
        flex-direction: row;
      }

      header div {
        flex: 1;
      }

      header aside {
        background: black;
      }
    </style>
  </head>
  <body>
    <header>
      <div style='background-image: url(https://i.cloudup.com/C9UpLWmovB.jpg);'>

      </div>
      <aside>
        
      </aside>
    </header>

    <section>
      <p>Hello World.</p>
    </section>
  </body>
</html>

I am trying to make it so I have 2 "sections" (the header and the section), both taking up the full viewport width/height. Then in the section (the second full page view), it centers the text vertically and horizontally. In the header (first full page view), it is laid out like this:

 _____________________
|               |     |
|               |     |
|    centered   |     |
|     image     | ad  |
|               |     |
|               |     |
|_______________|_____|

The image will be such that it fills whatever dimension will keep it centered. For example, like this:

 ___________________
|  _______________  |
| |               | |
| |               | |<-- image
| |               |<---- viewport
| |               | |
| |               | |
| |               | |
| |_______________| |
|___________________|

Or on a wider screen:

     ___ viewport
    |
    |
 ___|_______________<-- image
|___v_______________|
|                   |
|                   |
|                   |
|                   |
|                   |
|                   |
|___________________|
|___________________|

The image doesn't stretch but it zooms in and out so as to completely fill the viewport, which in this case is only part of the window since we have the ad space there.

Knowing how to do this will make it possible to position any image in a container so it fills the container properly.

Wondering how to accomplish this.

Right now it looks like this and it doesn't scroll right:

enter image description here


Solution

  • Have you tried setting background-size?

     header > div {
        background-position: center;
        background-size:cover;
        }
    

    or using media query to set background size based upon viewports?

    @media screen and (max-width: 992px) {
     header > div {
                background-position: center;
                background-size:70%;
                }
    }