Proper implementation of media viewport for images with backgrounds

Although I am not a front-end developer, I ventured into creating a simple one-page website with an image. To ensure faster loading on smaller screens, I made multiple versions of the image to minimize the amount of data being downloaded. The image is intended to expand horizontally, so I also designed background images that would repeat horizontally. Take a look at the mockup below:

https://i.sstatic.net/Wk00V.png

I have shared the code that I have written. Can you confirm if this is the correct approach? Is there any issue in my code or is it the right way to utilize viewports? While it functions well on my 320px iPhone screen, I am facing difficulties making the 320px version work on my desktop browser. Overall, I am not completely satisfied.

HTML:

<div id="image" class="fluid-container">
  <center>
    <picture id="banner">
      <source media="(max-width: 320px)" srcset="320w.jpg">
      <source media="(min-width: 1200px)" srcset="1200w.jpg">
      <source media="(min-width: 800px)" srcset="800w.jpg">
      <source media="(min-width: 480px)" srcset="480w.jpg">
      <img src="800w.jpg">
    </picture>
  </center> 
</div>

CSS:

<style>
    #image {
      background-image: url("r320w.png");
      background-repeat: repeat;
    }
    @media (min-width: 480px) {
      #image {
        background-image: url("r480w.png");
        background-repeat: repeat;
      }
    }
    @media (min-width: 800px) {
      #image {
        background-image: url("r800w.png");
        background-repeat: repeat;
      }
    }
    @media (min-width: 1200px) {
      #image {
        background-image: url("r1200w.png");
        background-repeat: repeat;
      }
    }
</style>

Answer №1

Check out this awesome code snippet : https://codepen.io/anon/pen/XqJRKM

In a nutshell, the trick is:

#image {
  background-image: url("http://lorempixel.com/output/sports-h-c-1-480-10.jpg");
  background-repeat: repeat;
  background-size:contain;
  width: 100vw;
  background-color:#f00;
}

@media (min-width: 480px) {
  #image {
    background-image: url("http://lorempixel.com/output/sports-h-c-1-480-5.jpg");
    background-repeat: repeat;
  }
}
@media (min-width: 800px) {
  #image {
    background-image: url("http://lorempixel.com/output/sports-h-c-1-480-6.jpg");
    background-repeat: repeat;
  }
}
@media (min-width: 1200px) {
  #image {
    background-image: url("http://lorempixel.com/output/sports-h-c-1-480-7.jpg");
    background-repeat: repeat;
  }
}

#image img{
  width:80vw;
  height:auto;
  max-width:1200px;
}

html :

<html>

<div id="image" class="fluid-container">
  <center>
    <picture>
        <source media="(max-width: 600px)" srcset="image1.png">
        <source media="(min-width: 600px) and (max-width : 800px)" srcset="image2.jpg">
        <source media="(min-width: 800px) and (max-width : 1200px)" srcset="image3.png">
        <source media="(min-width: 1200px)" srcset="image4.jpg">
        <img src="original_image.jpg">
    </picture>
  </center> 
</div>

Keep in mind that in this example, original_image.jpg will only be visible on outdated browsers. It will always be replaced on newer versions starting from Chrome v38

Answer №2

Replace uni-colored 1px images with background color for optimization. Code now supports four viewports and includes Bootstrap4 with Flexbox for vertical alignment and padding control.

<!DOCTYPE html>
<html lang="en>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Center Image</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
  </head>
  <body>
    <div class="container-fluid">
      <div class="d-inline d-md-none"> <!-- Small viewports -->
        <div class="row" style="height: calc(50vh - 150px)">
          <!-- Extra row to vertical align the 'image row' -->
        </div>
        <div class="row d-flex p-2 1pix" style="height: 300px; margin: 0 -15px; background-image: url('1px_sm.png'); background-repeat: repeat;">
          <div class="col-12 d-flex align-items-center justify-content-center">
            <img src="320px.png">
          </div>
        </div>
      </div>
      <div class="d-none d-md-inline d-lg-none"> <!-- Medium viewports -->
        <div class="row" style="height: calc(50vh - 200px)">
        <!-- Extra row to vertical align the 'image row' -->
        </div>
        <div class="row d-flex p-2 1pix" style="height: 400px; margin: 0 -15px; background-image: url('1px_md.png'); background-repeat: repeat;">
          <div class="col-12 d-flex align-items-center justify-content-center">
            <img src="480px.png">
          </div>
        </div>
      </div>
      <div class="d-none d-lg-inline d-xl-none"> <!-- Large viewports -->
        <div class="row" style="height: calc(50vh - 250px)">
          <!-- Extra row to vertical align the 'image row' -->
        </div>
        <div class="row d-flex p-2 1pix" style="height: 500px; margin: 0 -15px; background-image: url('1px_lg.png'); background-repeat: repeat;">
          <div class="col-12 d-flex align-items-center justify-content-center">
            <img src="800px.png">
          </div>
        </div>
      </div>
      <div class="d-none d-xl-inline"> <!-- XL viewports -->
        <div class="row" style="height: calc(50vh - 300px)">
          <!-- Extra row to vertical align the 'image row' -->
        </div>
        <div class="row d-flex p-2 1pix" style="height: 600px; margin: 0 -15px; background-image: url('1px_xl.png'); background-repeat: repeat;">
          <div class="col-12 d-flex align-items-center justify-content-center">
            <img src="1200px.png">
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

View the result here.

Note that in Bootstrap4, use the correct class 'container-fluid' not 'fluid-container.'

For different image sizes based on media, use this approach in Bootstrap 4:

<img src="150px.png" class="d-block d-md-none">
<img src="300px.png" class="d-none d-md-block">

Refer to the documentation here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a navigation bar - using the LI tag with spaces between words causes text to wrap to the next line

Currently, I am in the process of creating a dynamic navigation bar for my website. In order to ensure that the elements within the navigation bar adjust automatically based on content, I have implemented the code below: .mytaboptions { position: rela ...

"Bootstrap 4 with the ability to display multiple content sections under a

Currently, I am experimenting with bootstrap tabs and my goal is to have a single tab with multiple content divs. I attempted to achieve this by using two data-target values like data-target=".etab-p1, .etabi-img1". However, the solution only seems to work ...

Displaying divs of varying heights in a line

I'm facing a challenge in creating floating divs, just like illustrated in the image provided in the link below. Currently, I am employing the float left property to align all the divs next to each other. The first picture displays the default layout ...

Is it possible to display two menus on opposite sides of the screen while using Google Maps?

Currently, I am working on developing a Progressive Web App using Vue.js and Vuetify.js. My goal is to have two buttons overlaid on Google Maps - one on the left side of the screen to open a navigation drawer, and another on the right side to display user ...

The group-by-v2 plugin in the Bootstrap table example is not functioning as expected

I am currently utilizing the JQuery Bootstrap-table to group data, which can be found at this link: . Although the example on that page displays an additional row (not present in the JSON), it does not incorporate expand-collapse icons or functionality. ...

Problem with the mobile site width due to viewport misalignment

Our website is currently experiencing an issue with the viewport, but it seems to only occur on mobile devices: If you visit the site on your mobile device, you may notice a large gap on the right side of the page. Strangely, this problem does not appear ...

Creating a static HTML page using Flask and incorporating redirects

I have a web application built using Flask that processes a URL, performs some operations, and then redirects the user to another URL. I am looking for a way to display a simple "please wait" message in a static HTML page while the processing is happenin ...

Comparison between Responsive Design Mode and resizing the browser window

I'm experimenting with responsive design and trying to adjust elements based on screen resolution. For example, I have the following code snippet: @mediaquery only screen and (min-width:1125px) and (max-width:1280px) { flex-basis: 31.4rem; ...

The enigma of CSS: How is the width mysteriously set to 0px with no visible CSS styling

Take a look at this snapshot of a webpage I'm currently designing in Chrome Developer Tools: https://i.sstatic.net/SB00j.png The primary rule in the 'Matched CSS Rules' section indicates that the width of the element should be 160px. Howe ...

Online collection-based game

This is my first attempt at creating a web-based game and I have some questions about the necessary technologies. Specifically, I want to enable users to gather items and save their progress within the game. Currently, I am focusing on mastering HTML, CS ...

apply styling to the placeholder with CSS

I have been attempting to customize the styling of the placeholder text. After setting the color to red within the input class, I did not see any changes. Even after conducting research and referring to this link Styling the placeholder in a TextField, I w ...

Troubles with Borders and Padding in HTML Elements

Hello everyone, I'm currently facing an issue trying to neatly fit a textbox, select menu, and button all within the same sized div. Each element seems to have strange borders/margins causing them not to display properly (the button ends up below the ...

Issue with Jquery causing tabs to malfunction

Check out the CodePen I'm currently working on where I have included the following Jquery code to create a tab-style interface where each button displays specific content. Here's the Jquery code I'm using: $('.content-canvas').fi ...

An interesting approach to utilizing toggle functionality in JQuery is by incorporating a feature that automatically closes the div when

Currently, I am utilizing JQuery's toggle function to slide a ul li element. However, my desired functionality is for the div to close if someone clicks outside of it (anywhere on the page) while it is in the toggle Down condition. Below, you'll ...

Collaborate on documents with fellow users on the Django platform

Summary of the app: The main focus of this application is to enable users to create projects and share uploaded files with others, based on permission settings. Basically, after creating a project using the Project module, when a user uploads a file to the ...

Employing Bootstrap, incorporate a vertical divider in the center to split three icons on the left and three icons on the right, all while ensuring the design remains responsive

I have been struggling with a layout issue for the past couple of days and I am in need of assistance from someone who can help me. Unfortunately, I am unable to upload an image here as I am new and do not yet have enough reputation points. The Layout Str ...

Show four rows of each item, with any remaining item displayed on a separate row

<script> let pets = [ { id: 'OUtn3pvWmp1', name: 'Cat1' }, { id: 'OUtn3pvWmp2', name: 'Cat2' }, { id: 'OUtn3pvWmp3', name: 'Cat3' }, { id: 'OUtn3pvWm ...

Place a div at the bottom of a flexbox while adding some padding around it

Here's what I'm dealing with: .flex-container { display: flex; justify-content: center; padding: 5%; position: relative; } .box1 { position: absolute; bottom: 0; width: 100%; height: 100%; } <div class="flex-container"> ...

Skip over the em tags while extracting the content from the class name using the Parsel selector

Is there a way to extract the contents of a specific class name, including what's inside and after 'em' tags? Refer to the image below for context: https://i.sstatic.net/FrYVv.png My attempted methods and the corresponding outcomes are as f ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...