Switching images between mobile and desktop view in responsive mode is a useful feature for optimizing

Within a specific folder structure, I have a collection of images designated for both desktop and mobile displays:

img:
    img-1.png
    img-2.png
    img-3.png
    img-4.png
    img-5.png
    img-6.png

img/mobile:
        img-1.png
        img-2.png
        img-3.png
        img-4.png
        img-5.png
        img-6.png

To switch the desktop image img-1.png, I currently use this code:

<span id="switcher">
   <img id="houdini" src="img/img-1.jpg" alt="">
</span> 

<span id="switcher2">
   <img id="houdini2" src="img/img-2.jpg" alt="">
</span>

<span id="switcher3">
   <img id="houdini3" src="img/img-3.jpg" alt="">
</span>

<span id="switcher4">
   <img id="houdini4" src="img/img-4.jpg" alt="">
</span>

<span id="switcher5">
   <img id="houdini5" src="img/img-5.jpg" alt="">
</span>

Regarding CSS:

@media only screen and (max-device-width: 489px) {
    span[id=switcher] {
        display:block;
        background-image: url(/mobile/img-1.jpg);
        background-repeat: no-repeat;
        background-position: center;
    }
    img[id=houdini] {display: none;}
}

Is there a way to streamline writing the above CSS for all images from img-1 to img-6? Can an ID be passed or accessed?

Can we eliminate the use of !important in the code?

(Need compatibility with IE8)

Answer №1

Why not try a different approach for displaying images on desktop? You can have pairs of images for desktop and mobile side by side, toggling their visibility using specific classes:

Check out this example

<img src="http://placehold.it/200/f30" alt="houdini" class="visible-mobile">
<img src="http://placehold.it/200/3f0" alt="houdini" class="hidden-mobile">
.visible-mobile {
  display: none !important;
}

@media (max-width: 489px) {
  .visible-mobile {
    display: inline !important;
  }

  .hidden-mobile {
    display: none !important;
  }
}

Answer №2

<picture>

  <source srcset="https://uniquewebsite.com/images/devices/new-imac.png" media="(min-width: 1000px)">
  <source srcset="https://uniquewebsite.com/images/devices/new-macbook-grey-front.png" media="(min-width: 500px)">
  <source srcset="https://uniquewebsite.com/images/devices/new-iphone6plus-spacegrey-portrait.png" media="(max-width: 500px)"> 

  <img src="https://uniquewebsite.com/images/devices/new-macbook-grey-front.png" alt="Unique Tech Product" id="unique-image" class="unique_image" style="max-width: 100vw; max-height: 100vh;">

</picture>

For a unique look, consider using min-device-width and/or max-device-width to prevent image changes upon browser resize. Give it a try!

Answer №3

You have the ability to dynamically manipulate it

$('body').append("<style type='text/css' id="+uniqueid+">@media screen and (max-device-width: 489px) { span[id="+uniqueid+"] {/* styles */ } }</style>");

To delete the style

$('#uniqueid').detach();

Alternatively

$('#uniqueid').remove();

Answer №4

<span id="flipper" class="myflip">
   <img id="merlin" src="img/img-1.jpg" alt="">
</span>

<span id="flipper2" class="myflip">
   <img id="merlin2" src="img/img-2.jpg" alt="">
</span>

<span id="flipper3" class="myflip">
   <img id="merlin3" src="img/img-3.jpg" alt="">
</span>

<span id="flipper4" class="myflip">
   <img id="merlin4" src="img/img-4.jpg" alt="">
</span>

<span id="flipper5" class="myflip">
   <img id="merlin5" src="img/img-5.jpg" alt="">
</span>

CSS =

  @media only screen and (max-device-width: 489px) {
    span.myflip {
      display:block;
      background-image: url(/mobile/img-1.jpg) !important;
      background-repeat: no-repeat !important;
      background-position: center !important;
    }
    img[id=merlin] {display: none !important;}
  }

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

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

The troubleshooting of compatibility issues between TailwindCSS and HTML Input and Button tags

Recently, I decided to switch from using plain CSS to TailwindCSS for styling the navbar component that I obtained from the Bootstrap website. While TailwindCSS has helped me style most parts of the navbar successfully, I have encountered a challenge with ...

Issue with the button border not functioning correctly upon hover

I'm currently practicing my HTML and CSS skills, with a focus on creating buttons. I have encountered an issue where I want a colored border to appear around the button when hovered over. Unfortunately, I seem to be stuck and unable to achieve the des ...

CSS animations are failing to work properly in Firefox due to a pseudo-element issue

I'm encountering a problem with my CSS animations in Firefox. Specifically, the animations are not working on a pseudo element (:after) while they work perfectly fine on other browsers. Below is where the animations are being applied: :after { d ...

When using the navbar in Tailwind CSS, the image is appearing distorted instead of aligning properly with the adjacent

I am trying to add a flag, login button, and sign up button Using class="flex", I placed an image inside it However, when I add the buttons, the image gets distorted. How can I prevent this? Expected Outcome I want to create the flag, login but ...

Customize Tab indicator styling in Material-UI

Currently, I am attempting to customize the MUI tab by changing the indicator from a line to a background color. Through my research, I discovered that using TabIndicatorProps and setting a style of display:none eliminates the indicator completely. However ...

What is the best way to locate the final text node within the <p> element?

Looking at the code below, my goal is to identify and retrieve the text node that serves as the last child element. <p class="western" style="margin-bottom: 0.14in"> <font color="#000000"> <font face="Arial, serif"> <font ...

Troubleshooting a CSS problem on a table filled with images - See attached screenshots for

I've been working on a project involving my phpmyadmin database generating a series of 6 images on my website. I've placed them in a table, but now I'm facing some challenges - even though it seemed simple at first! The goal is to display t ...

implementing a time picker feature with jQuery

As I am not familiar with jQuery, I came across this script while searching for a time picker. If anyone could guide me on how to incorporate this code into my HTML page to enable the time picker functionality, I would greatly appreciate it. /* jQuery t ...

Tips for avoiding accidental unit conversion in jQuery

Imagine having the following code: var $element = $('<div/>'); $element.css("margin-left", "2cm"); console.log($element.css("margin-left")); When tested in Chrome, it doesn't return anything, but Firefox shows "75.5833px". Any sugges ...

Generate several invoices with just a single click using TypeScript

I'm interested in efficiently printing multiple custom HTML invoices with just one click, similar to this example: Although I attempted to achieve this functionality using the following method, it appears to be incorrect as it prompts the print dialo ...

How can I position four DIV elements to the right of each other inside a parent DIV?

I am attempting to align 4 divs next to each other within a parent div at specific positions. The proposed div structure is as follows (referred to as the maindiv): <div> <div>1</div> <div>2</div> <div>3< ...

Animating an image with CSS steps to create a captivating shaking

My attempt at creating a basic animation is not producing the desired smoothness. .animate { animation: motion 1.5s steps(27) forwards; } @keyframes motion { 100% { background-position: -5778px; } } <div class="animate ...

Tips on aligning text to the left on mobile devices using CSS and HTML

When viewed on a standard 16:9 computer screen, everything looks perfect with text on the left and an image on the right. However, when it comes to smaller screens like phones, the picture appears on top of the paragraph instead. I am new to this, so any a ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...

Unable to overlay a div on top of an image

Hello, I'm currently attempting to overlay a div on top of an image. Since the image needs to be responsive, it cannot be set as a background image. Here is the CSS I am using: #slider { margin:0 33%; width:67%; position:relative; } #sli ...

Embed video with a custom thumbnail in an iframe

Hello everyone! I'm a first-time user on stackoverflow seeking some help. Currently, I am using Dreamweaver to work with HTML and CSS in order to build a website. My task involves sourcing a video from a television archive and embedding it onto my si ...

The stickiness of elements causes scrollbars to disappear in Chrome 77 on OSX

In this scenario, I have set up two tables where the first one has a sticky header achieved with position: sticky; top: 0px; https://codepen.io/seunje/pen/JjjRVLm The sticky header works perfectly fine, but there is an issue with scrollbars disappea ...

What causes the disruption of vertical alignment among inline-block elements when using overflow:hidden?

Take a look at these two JSFiddles: http://jsfiddle.net/am28dsbz http://jsfiddle.net/am28dsbz/1/ Why is it that the first one shows my text aligned correctly, while the second one displays the first link lower than the second? Stack Overflow requires m ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...