Search code examples
cssresponsive-imagesbackground-size

Is there anyway to set background-size to both contain and cover?


Here is a pen to my attempt https://codepen.io/alexyap/pen/VbvGvw

<div id="bg">
</div>



* {
  margin: 0;
  padding: 0;
}

#bg {
  background: url('https://static.pexels.com/photos/198747/pexels-photo-198747.jpeg');
  height: 60vh;
  width: 100%;
  background-repeat: no-repeat;
  background-size: 100vw;
}

I nearly had it figured out but I just can't seem to copy how this website https://sierradesigns.com/ did it (check slider images on landing page), mine is cut off on the bottom no matter what value i give the height


Solution

  • By setting the background size to cover you are giving the browser the prerogative to adjust the image until it completely covers the area; it will ignore width and height values you assign.

    With contain you allow the browser to decide how to adjust the image so that the entire image fits within the area, which may be based on height or width to accomplish this (depending on the orientation of the image wide or tall).

    background-size: 100% 100% is probably what you're looking for, but that will disproportionately adjust the image (ie: stretch or compress depending on orientation). However, it does sound like that's what you want when you say "both cover and contain".

    There are many ways to place and scale images used as backgrounds (where background does not necessarily mean the CSS background property)

    Below is a simplified example of how I've accomplished this (assuming images that are roughly 700x300 px)

    .container-wrap {
         width:100%;
         }
     .container {
         position:relative;
         padding:42.86% 0 0 0;
         /* where padding = the proportion of the images width and height
         which you can get by division: height / width = 0.42857 */
         }
     .container img {
         position:absolute;
         top:0px;
         right:0px;
         bottom:0px;
         left:0px;
         }
    

    it is important that your images maintain a close proportion to each other -- if they are slightly off, the slight distortion shouldn't be visible to most people for most images

    Again, there are other methods to accomplish this. The website you linked to applies a similar concept. The concept is the same, method is slightly different (for example they are using width:100% on the images instead of absolutely positioning them), where the concept = "using some sort of method to proportion the images to the container so it will magically scale"

    Note that the same method can be applied to video containers (such as from YouTube).