barskyn
barskyn

Reputation: 383

Responsive Banner HTML/CSS

I am trying to make a banner for a webpage. I wanted create a container that only look up 20% of the page height-wise and then the image within it would take up 100% on the container. However, the image just ends up taking up all of the page and not responding to % changes.

Html code:

<div class="banner">
<img src="img/header.jpg">
  </div>

CSS code:

.banner {
  width: 100%;
  height: 20%;
}


.banner img {
  height : 100%;
  width: 100%;
}

Upvotes: 3

Views: 33339

Answers (4)

Pons Purushothaman
Pons Purushothaman

Reputation: 2261

Your .banner is not taking the height 20% from css. The reason is it does not have a parent element having height set. So here I have added height: 100% to html and body. Try the below example.

html,body{
  height: 100%;
}
.banner {
  width: 100%;
  height: 20%;
  background: green;
  font-size: 0;
}


.banner img {
  height : 100%;
  width: 100%;
}
<div class="banner">
  <img src="https://cdn.pixabay.com/photo/2015/12/13/09/42/banner-1090835_960_720.jpg">
</div>

Upvotes: 0

Archit Arora
Archit Arora

Reputation: 2626

Instead of using the <img> tag you can set the image as the background of your container.

.banner{
background-image: url("/img/header.jpg");
}

Upvotes: 0

Hans Yulian
Hans Yulian

Reputation: 1180

if you dont want to use a floating banner, you might consider to change your styling as this:

.banner {
  width: 100%;
  height: 20vh;
}

vh = view height. https://www.w3schools.com/cssref/css_units.asp.

and if you want floating banner to follow as your page scroll, use this:

.banner {
  width: 100%;
  height: 20vh;
  position:fixed;
}

Upvotes: 6

Vishal Taj PM
Vishal Taj PM

Reputation: 1359

You can use vh instead of percentage for banner. 1vh = 1%

.banner {
  width: 100%;
  height: 20vh;
}


.banner img {
  height : 100%;
  width: 100%;
}
<div class="banner">
  <img src="http://via.placeholder.com/350x150">
</div>

Upvotes: 0

Related Questions