Displaying a fully customizable loading background color that adapts to various screen sizes while an

I have an application where I fetch an image and its size from a JSON. My issue is that when the image is loading, there is a gap left behind that I would like to fill.

The problem arises when I try to use a div with fixed width and height to fill this gap. It ends up not being responsive if the image has styles like height: auto; max-height: XXXpx;. So, how can I maintain responsiveness without compromising the width / height proportion?

NOTE: I want this solution to work for any width and height combination while still preserving the ratio / proportion.


UPDATE:

Let me illustrate my problem with an example. As you can see, the div has a fixed size which causes overflow when the window width or height is less than 256px, even though the image remains responsive. So, how do I make the div responsive without losing this proportion?

<html>
  <head></head>
  <body>

    <!--
      This div contains the image and by default uses the `container` class (explained below) with a fixed width and height matching the image size.
      This class will be removed once the image loads to make it "responsive".
    -->
    <div
      id="container"
      class="container"
    >
      <!--
        The image utilizes the `image` class with necessary responsive styles, and triggers "removeDummyClass()" on load.
      -->
      <img
        class="image"
        src="https://sftextures.com/texture/2574/0/2578/dog-foot-pad-on-white-snow-frozen-ground-dark-footprint-sign-icy-cold-winter-pattern-seamless-texture-256x256.jpg"
        onload="removeDummyClass()"
      />
    </div>


    <script type="text/javascript">
      // Function to remove class with a dummy image (background-color in this case)
      const removeDummyClass = () => {
        document
          .getElementById('container')
          .classList
          .remove('container')
      }
    </script>

    <style>
      .container {
        background-color: red;
        width: 256px;
        height: 256px;
      }

      .image {
        height: auto;
        max-width: 100%;
      }
    </style>

  </body>
</html>


UPDATE 2:

To better illustrate the issue, I am including some screenshots, not for debugging purposes, but to clarify the problem.

Initially, the div overflows due to manually set width and height.

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

Once the image loads, it resizes without losing the width-to-height proportion.

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

Answer №1

To achieve this, I utilized a small snippet of javascript:
The approach involves concealing the content of the page and revealing your chosen background element.
If the body of the page is not yet prepared, a script interval runs every second until it is ready. Once the body is ready, the display property of the page transitions from display:none to display:block

function onPageLoad(callback) {
var intervalID = window.setInterval(checkPageReady, 1000);

function checkPageReady() {
if (document.getElementsByTagName('body')[0] !== undefined) 
{
window.clearInterval(intervalID);
callback.call(this);
}
}
}

function modifyDisplay(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}

onPageLoad(function () {
modifyDisplay('page', true);
modifyDisplay('loading', false);
});
#page {
display: none;
}

#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
background-image: url("URL_TO_YOUR_IMAGE");
background-repeat: no-repeat;
background-position: center;
}

.loading-page {
background: #72c3c9; /*The background color*/
width: 100vw;
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<title>Document</title>
</head>
<body>
<div id="page" style="display:none">
    <!-- YOUR PAGE CONTENT GOES HERE -->
</div>
<div id="loading" class="loading-page">
</div>
</body>
</html>

Answer №2

After much trial and error, I was able to make it work by utilizing an SVG filled with a rectangle that matched the desired height and width. I then used the onload event to remove the SVG element by setting its display property to none, and showing the image by setting its display property to block.

<html>
  <head></head>
  <body>

    <style>
      .image {
        border-radius: 15px;
        box-shadow: 0 0px 15px rgba(0, 0, 0, 0.4);
        height: auto;
        width: 100%;
        max-width: 256px;
      }

      .image-final {
        display: none;
      }

      .image-dummy-rect {
        fill: red;
      }
    </style>

    <div>
      <svg
        id="image-dummy"
        class="image"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 256 256"
      >
        <rect
          id="image-dummy-rect"
          class="image-dummy-rect"
          width="256"
          height="256"
        />
      </svg>
      <img
        id="image-final"
        class="image image-final"
        src="https://sftextures.com/texture/2574/0/2578/dog-foot-pad-on-white-snow-frozen-ground-dark-footprint-sign-icy-cold-winter-pattern-seamless-texture-256x256.jpg"
        onload="removeDummyClass()"
      />
    </div>


    <script type="text/javascript">
      const removeDummyClass = () => {
        document.getElementById('image-dummy').style.display = 'none'
        document.getElementById('image-final').style.display = 'block'
      }
    </script>

  </body>
</html>

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

What is the best way to split a Bootstrap navbar into two separate rows?

I'm struggling with breaking the navbar to have the navbar-brand in one row and the collapse menu in another. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72101d1d0601060013 ...

Folding animation using CSS3 and vertex manipulation

Looking to create a folding animation on a squared div with vertex? While there are examples online using Flash, I'm seeking guidance on how to achieve a similar effect using CSS3 and HTML5. Any tips or resources would be greatly appreciated. Thank y ...

What is preventing my CSS Animation from activating on my website?

Is there something in the code preventing the animation from working properly? .projectLinks a{ background-color: var(--secondary-color); color: var(--main-color); padding: 2px 4px 4px 4px; border-radius: 15px; margin-right: 25px; text-decorati ...

What is the purpose of including TTF files in a font-face declaration?

Suppose we implement the following font-face configuration (generated through fontsquirrel.com) @font-face { font-family: 'FrescoSansProNormal'; src: url('frescosanspro-normal-webfont.eot'); src: url('frescosanspro-normal-we ...

Learn the process of dynamically populating an HTML table with data using JavaScript and JSON

I have developed a code snippet to dynamically add an HTML table without using jQuery. The code serves as an application from the server to the client, where the client receives a JSON object to parse into a string. Here is how you can add an HTML table ...

Ensure that divs can adjust in size while maintaining the same dimensions of their contained

I'm currently facing a slight issue with these two divs. I want them to be scalable, which I know can be achieved by using percentages, but every time I do so, the divs end up out of position. When I try setting widths, they look fine in Google Chrome ...

I am encountering an issue with my jQuery datatable where the amount column only displays rounded values. I would like for the values to appear in currency format, such as $233.25,

I'm facing an issue with my jQuery datatable where the amount column displays only round values instead of the desired currency format like $233.25 showing up as $234. Here is the HTML table head section: <thead> <tr> <th> ...

Ways to move to the next line following the navigation bar text

Below is the code snippet that I am working with: <nav class="navbar navbar-expand-sm navbar-dark "> <div class="container-fluid"> <a class="navbar-brand" href="#">LOREM IPSUM</a&g ...

Utilizing jQuery to clear out data sent through the $.post

I am currently working on developing a multi-part form that involves executing different scripts for each part. Each script checks for essential data and if this data is missing, it should return a string "false". While part 1 fails correctly by calling h ...

The CSS on my website is causing issues with the recaptcha functionality

Recently, I've been working on a website that requires spam protection for the contact form. To combat this issue, I decided to integrate reCAPTCHA into the form. However, after completing the form and applying the necessary CSS styles, I noticed tha ...

Restricting the type of user input in HTML forms

Requirements: Input must be a whole number between 2 and 99, inclusive. Current Solution: <input required type="number" min="2" max="99" oninput="this.value = Math.abs(this.value)" maxLength="2" matInp ...

Perform JavaScript Actions upon Submission of a Stripe Form

I have implemented a custom checkout button for Stripe and I am looking to trigger a JavaScript function after the checkout process is successfully completed. Specifically, I want the function to change the style of the "book-appointment-button" from "no ...

Using the CSS property hyphens: auto does not function properly for certain words

Could someone shed light on why the word "Sustainability" is not being correctly hyphenated in the following code snippet? I have tested it in multiple browsers like Google Chrome, FireFox, and Safari, and none of them seem to hyphenate the word, ...

Tips for concealing the fourth child element within a list item

I'm facing an issue with a list of items rendered in my react component where I need to hide the 4th child of the list item. Here is the relevant html code: <div class="ExpandableContent-Content MyAccountTabList-ExpandableContentContent&qu ...

What is the best way to centralize the storage of my website's header and footer?

Constantly updating headers and footers requires me to manually transfer the code to each web page every time, which is not the most efficient method. I'm considering using a "header" and "footer" div, and using jQuery's $(document).ready functio ...

Extract the content from a <Span> element without specifying its ID

Is there a way to make it so that when a user clicks on an HTML tag, the text is copied to their clipboard? I also need to ensure that this functionality does not apply to a specific tag ID/name as I am unable to add those to my span. Is there a way to aut ...

Create a unique web page layout by utilizing divs and spans

Can the design shown in this image be created? https://i.sstatic.net/hsIaQ.png I've tried the code below but it's not functioning properly. Any assistance would be appreciated! The issue is that the Q and A text should be in a box that automati ...

What is the best way to incorporate multiple CSS files into a single HTML file in Django3?

My template folder contains an HTML file called index.html, along with two CSS files named computer.css and mobile.css stored in the static folder. I want to know how I can incorporate both CSS files into the single index.html file. ...

Adding a sub-menu to a dropdown menu in your Blogger website can enhance navigation and improve

Having some trouble adding a "sub menu" to my drop down menu. I have limited knowledge of CSS and can't seem to figure it out. My goal is to make the sub-menu open to the right side when the cursor is placed on it. Below is the related CSS and HTML co ...

Update the text content in the specific span element when the class attribute matches the selected option in the

How can I dynamically update text inside a span based on matching classes and attributes without hardcoding them all? An ideal solution would involve a JavaScript function that searches for matches between span classes and select field options, updating t ...