AntBirch AntBirch - 5 months ago 15
HTML Question

Keeping aspect ratio of image in full screen

I'm looking to put together a webpage which consists of the following (top to bottom):


  • image/background-image (full screen width, keeping aspect ratio)

  • navigation bar (on top of image, right aligned)

  • some text

  • another full screen image (same as the first)

  • footer



The issue I'm having is that if I use background-image I have to specify the image height in px. If I use img instead I can only seem to get this working (with the navigation bar on top) using absolute positing which in turn doesn't allow me to place the second div's below the first.

Apologies for the quickly put together image, I hope it shows what I'm aiming to do.

enter image description here

Answer

To keep the use of the img tag what you need to do is position your "header" elements over the content with absolute position not position absolute the img's container:

header {
  position: absolute;
  width: 100%;
  background: rgba(0, 255, 255, .5);
  line-height: 75px;
  text-align: center;
  font-size: 3em;
}
div img {
  width: 100%;
}
<header>Logo & Nav</header>
<div>
  <img src="http://lorempixel.com/1000/500" alt="">
</div>
<div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem quam, temporibus tenetur qui, sed magni. Praesentium, veritatis perferendis qui? Et accusantium, dicta natus libero iste atque voluptatem est. Dolore, consectetur.</div>
  <div>Eius obcaecati itaque assumenda fuga quam necessitatibus nam consectetur ab velit nostrum minus maxime ex temporibus autem iure, rem ea nihil totam sapiente perferendis praesentium ullam labore amet corrupti! Numquam!</div>
  <div>Esse accusantium excepturi sint deserunt praesentium repellat eius quibusdam ratione hic, modi blanditiis numquam tempore iusto, nisi dolore! Autem quis cumque mollitia atque perspiciatis vero animi eius quidem itaque enim.</div>
  <div>Deleniti magni ipsum illum odio, rerum ullam praesentium expedita vel impedit vitae ad eveniet voluptatem reiciendis reprehenderit omnis doloremque cumque assumenda, eligendi quas cupiditate sed numquam facere porro accusantium! Aliquam!</div>
  <div>Expedita nisi excepturi repudiandae quod provident animi numquam consequatur quidem, magnam non optio, saepe autem laudantium quis perferendis beatae veniam, quae assumenda deleniti eius cupiditate. Est, beatae deserunt facere magnam.</div>
</div>
<div>
  <img src="http://lorempixel.com/1000/1000" alt="">
</div>

Comments