drarkayl
drarkayl

Reputation: 1017

how to set a background for a div and have it resize according to browser size?

Im trying to design a home page for my website where im using a div to show an illustration.

i want to use an image with the div that covers the entire size of the div.

the image dimensions are 1920x850.

this is the code for the div

<div class="custom-col col-md-12 col-sm-12"  id="widget-static-block-1"></div>

the css:

#widget-static-block-1 {
 background: url({{ d_banner1.jpg' | asset_url }}); 
 width:100%; }

i want to be able to view the image on different screen sizes , but the it always gets cut off (either height or width)

ive tried playing around with height and width attributes to no luck.

If i set height:850px; then obviously it shows perfectly on a 1080p sceen but gets cut off on a smaller screen.

One thing i want to be clear about is that i want the entire image to show at all times at all browser sizes, i dont want it to be cut off via height or width.

Upvotes: 0

Views: 70

Answers (3)

LJ Jones
LJ Jones

Reputation: 295

It seems like you're asking for the div to fill the parent (height or width). And if you don't want the background image to appear cropped, you need to maintain the aspect ratio.

This looks what you need: Maintain aspect ratio of div but fill screen width and height in CSS?

Upvotes: 0

3rdthemagical
3rdthemagical

Reputation: 5350

Working example

Add styles to div with background:

background-repeat: no-repeat;
background-position: center center;
background-size: cover;

You can resize window to see result.

html, body {
  position: relative;
  height: 100%;
  margin: 0;
}

div {
  position: absolute;
  width: 100%;
  height: 100%;
  
  top: 0;
  left: 0;
  
  background: url('http://ghk.h-cdn.co/assets/16/09/980x490/landscape-1457107485-gettyimages-512366437.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}
<div>

</div>

Upvotes: 0

Kamila Korzec
Kamila Korzec

Reputation: 99

Try background-size: 100% 100% or background-size: 100vw 100vh. If you want to be certain your div suits every media you can use vw and vh units.

Upvotes: 1

Related Questions