skip to Main Content

I tried and looked up all that I could and still not finding any solutions or clues. Someone out there knows and. I appreciate the understanding, thank you.

Code for div’s that house the backgroundImage for the slider – I have tired object-fits, covers..., even in a css file but cannot get the responsiveness to work on the md, lg screens for Tailwindcss or css on the image’s height as the screen gets bigger.

Video shows the response issue as the screen grows and shrinks. Mobile view is what it should be and works as Tailwindcss is mobile first, but cannot control for the larger screens at the moment. Need help on that.

import React, { useState, useEffect } from 'react';
import '../components/HomeSlider.css';
import { images } from '../helpers/HomeSliderData';

let count = 0;

function HomeSlider() {
  const [currentImage, setCurrentImage] = useState(0);

  useEffect(() => {
    startSlider();
  }, []);

  const startSlider = () => {
    setInterval(() => {
      handleNextImage();
    }, 4000);
  };

  const handleNextImage = () => {
    count = (count + 1) % images.length;
    setCurrentImage(count);
  };

  return (
    <div className="max-w-screen-xl h-[420px] ml-auto mr-auto relative">
      <div
        className="w-full h-full flex  bg-center duration-800 absolute"
        style={{
          backgroundImage: `url(${images[currentImage].backgroundImage})`,
        }}
      ></div>
    </div>
  );
}

export default HomeSlider;

Video Demo: https://youtu.be/TZcbqXPAFbc

2

Answers


  1. You’d probably want to rework your h-[420px] class. This is a static height, but the width of the element will scale – thus the difference in image proportion when the width is a lot wider. You could consider applying an aspect-ratio value via an aspect-* class instead of defining a static height.

    Login or Signup to reply.
  2. If you want to keep the height of the image at 420px, you can look into serving responsive images. You would basically have different images for different screen sizes.

    For background image you have the image-set but the support is not the best. If you can change to an img tag, then the support is better for srcset.

    Check out the below code snippet result by resizing your window.

    <img 
      alt="sample image" 
      src="http://via.placeholder.com/1080x420"
      srcset="
        http://via.placeholder.com/640x420 640w, 
        http://via.placeholder.com/1080x420 1080w,
      "
      />

    extra: a related funny post I’ve seen on reddit a while ago

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search