Setting the dimensions of an <img> based on the ratio of its base64 encoded background data

After hours of brainstorming, I have encountered a dilemma while creating a 2-column layout page.

I am looking to implement a fixed background image loading technique to prevent users from mistakenly clicking on links before the images are fully loaded. Have you ever experienced the frustration of clicking on a link only to have the target change as an image loads, leading to even more confusion?

To visualize my question better, I have uploaded an image for reference:

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

The provided code is as follows:

.wrapper {
  text-align:center;margin:30px auto 0;width:410px;
  background:#ffe;
}
.wrapper a {width:49%;display:inline-block;margin:1px}
a {display:inline-block}
b {display:block}

.wrapper-desired-look a img {
  width:100%;
  height:105px;
}

/* Base64 Image */
.wrapper a img {
  background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAbgAAADmCAMAAACQ52CyAAAAOVBMVEXu7u7R0dHOzs7V1dXJycni4uLb29vY2NjNzc3p6enf39/d3d28vLzr6+vl5eXQ0NDGxsbAwMC4uLgSPp6uAAAGWklEQVR42uzYAW6EIBBGYZhZoGjA3v+0tduk00pSdxHXNHnfFZ7+meAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ESpuovV6PC84GPI7jJ5Snr5p/M/+Td/Vbsc0iKeH65PfF/LeY2huJcqIXkR8RocetTbWu4u1pe1KzV6+eRVs0OP4r/LeZ3Pb2fVvrqxlL3i7V7O2rlT1agi1k0nh96ttHJnt8uzillUlZuy33Jbif8pTdkNlycV2XZLxaF7K1fv4n9LIY+tlkS23VjKo1tp/9zodnb6t91YyoMWK7cVQzleLVq1bbfkcGQrrVwr1nL49G+pspRDttLKtdTa9Z7+bTeW8rji23Jtu6erzSqm7cZNOWIrd8rZs0rX6d92YymHbWVbrpWm+uCrv/xFlaUcxO+Ws3ZhT/Ky042lHL+VVq7f8mA3nR1GbKWVO7GdKkv5wc65JSkOA0Ew5Jb1sMPW3v+0S4Ch2dY41tZ0/VVyhIwsmsGMIy1+0UKAuRPhUiK2UpvDyBPhUkK2UpuDuBPhUvqyNYQ5606ES6kgtvKPmnN0FzKX0p09GnPBmxaES+nPFmKEHChK5lIiSGhxkoVLqaC2shRvczlzKRFszYgrzsEZcZkPwjqRrbjmHNy3OT4IC9rKUpy3Uow...
<h2>
The look without fixed width and height
</h2>
<div class="wrapper">
<a>
  <img src="" alt=" How do I keep the ratio of the pre-set base64 background image? " />
  <b>Title 1</b>
</a>
<a>
  <img src="" alt="And let it resized to the desired width" />
  <b>Title 2</b>
</a>
<a>
  <img src="" alt="with pure CSS?" />
  <b>Title 3</b>
</a>
</div>


<h2>
The desired look
</h2>
<div class="wrapper-desired-look wrapper">
<a>
  <img src="" alt=" This look is what I expected " />
  <b>Title 1</b>
</a>
<a>
  <img src="" alt=" But I need to pre-set the width and height " />
  <b>Title 2</b>
</a>
<a>
  <img src="" alt=" property in the CSS" />
  <b>Title 3</b>
</a>

Is there a way to achieve the desired look without relying solely on CSS?

If JavaScript is necessary, what approach would you recommend?

Answer №1

To ensure the correct ratio of an <img> tag, you must load it in the src attribute rather than setting it as a background image. I have moved the background image to the container (<a>) and added the <img> element as a non-visible responsive element within it. This adjustment ensures that the image sets the correct ratio on the parent element, providing the desired result you are looking for. It is important to note that the browser only loads the image once, regardless of it being used in the src or background-image.

$(window).on('load', function(){
  $('.wrapper>a').each(function(){
    imagePath = $(this).css('background-image').replace('url("', '').replace('")','');
    if (imagePath.length > 0) {
      img = $('<img />', {
        class:'hidden',
        src:imagePath
      });
      $(this).prepend(img);
    }
  })
})
.wrapper {
  padding: 1rem;
  display: flex;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
}

body {
  padding: 0;
  margin: 0;
}
.wrapper > a >img {
  visibility: hidden;
  z-index: -1;
  position: relative;
  width: 100%;
  height: auto;
  float: left;
}
.wrapper > a > h4 {
  position: absolute;
  bottom: -4rem;
  text-align: center;
  width: 100%;
}
.wrapper > a > .visible-content {
  width: 100%;
  position: absolute;
  font-size: 1.4rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.wrapper > a {
  margin: 1rem 1rem 4rem;
  width: calc(50% - 2rem);
  display: block;
  position: relative;
  background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAbgAAADmCAMAAACQ52CyAAAAOVBMVEXu7u7R0dHOzs7V1dXJycni4uLb29vY2NjNzc3p6enf39/d3d28vLzr6+vl5eXQ0NDGxsbAwMC4uLgSPp6uAAAGWklEQVR42uzYAW6EIBBGYZhZoGjA3v+0tduk00pSdxHXNHnfFZ7+meAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ESpuovV6PC84GPI7jJ5Snr5p/M/+Td/Vbsc0iKeH65PfF/LeY2huJcqIXkR8RocetTbWu4u1pe1KzV6+eRVs0OP4r...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <a>
    <div class="visible-content">
      How do I keep the ratio of the pre-set base64 background image?
    </div>
    <h4>Title 1</h4>
  </a>
  <a>
    <div class="visible-content">
      And let it resized to the desired width
    </div>
    <h4>Title 2</h4>
  </a>
  <a>
    <div class="visible-content">
      with pure CSS?
    </div>
    <h4>Title 2</h4>
  </a>
</div>

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

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Tips for accessing the ID, Name and Class of a specific DIV element with the class "Extreme" upon clicking a button

Need help finding the ID of the outermost parent div <div class="panel" id="Kudapanel"> //Top-level Div <div class="Kudapanel1" id="Kudapanel1"> </div> <div> <div> <input type="button" id="yo ...

Automatically changing the color of the navigation bar text

I am experiencing an issue with the navigation bar on my webpage. Currently, it is styled with white text against a dark background color using the following CSS code snippet: a{ color: white; text-decoration:none; font-weight:bold; font-s ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

Guide to showcase Material UI drawer with a margin at the top

I'm having trouble implementing a Material UI drawer with some top margin instead of starting from the very top of the page. I've tried applying the marginTop property, but it's not working. You can view my code on CodeSandbox here: Drawer. ...

What is the best way to change the row background color in an ng-prime datatable with dynamically changing columns?

Is there a way to dynamically change row colors in a table when a row is updated successfully? <p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]="{'overflow':'hidden!important'}" ...

Using keyframes for flexbox animation in Safari

What could be causing the issue with flex keyframes not working in Safari while functioning properly in other browsers? <div class="a"> <div class="b"></div> </div> .a { height: 200px; display: flex; } .b { flex:0 1 50% ...

"Aligning content in Bootstrap with vertical centering

I am currently working on aligning a simple piece of code vertically. Check out the code on JS Fiddle: https://jsfiddle.net/3kj44net/ .container-fluid { padding-left: 20px; padding-right: 20px; } <link href="https://maxcdn.bootstrapcdn.com/boots ...

What is the best way to display SQL data in PHP using div elements?

I am currently working on a project that requires me to display posts from a database. Each post consists of a title and text content. I have successfully retrieved the necessary information from the database using PHP and SQL, however, I am struggling wit ...

Adaptable dropdown menu

I am currently utilizing unsemantic.css for my web layout. Here is a basic structure I have set up: <div class="grid-container"> <div class="grid-65"> Insert content here </div> <div class="grid-35"> <select> ...

Revolutionizing the Industry: Discover the Power of Dynamic Models, Stores, and Views for

As a newcomer to EXT JS, I am exploring the use of MVC in my projects. Consider a scenario where I have a web service with a flexible data model. I would like to dynamically create models, stores, and components based on the data from these stores. Let&a ...

There was a problem accessing the website

Recently, I tried to access a web page from the server using command prompt by following a tutorial on YouTube. However, I encountered an error message while trying to open the page. The specific error is displayed below. Can someone please guide me on res ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Retrieve the generated HTML output by executing an EmberJs.Handlebars template in Ember.js

I've been on the lookout for a while now, trying to figure out how to extract HTML when evaluating a template. Handlebars makes this task very simple: var source = $("#entry-template").html(); var template = Handlebars.compile(source); var context ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...

Tips for creating a dynamic sidebar animation

I have recently delved into the world of web design and am eager to incorporate a sidebar into my project. While browsing through w3school, I came across a design that caught my eye, but I found myself struggling to grasp certain concepts like the 'a& ...

Why does the flex-start and flex-end values correspond to the top and bottom positions when using the flex-direction property set

I am attempting to organize text and buttons into a row, with the buttons aligned on the right side and the text on the left side. My approach involves creating a flexbox layout and assigning items the appropriate classes for alignment. html, body { widt ...

What is the best way to interpret numerous rows of Form elements simultaneously?

What is the most efficient way to name form elements across rows for easy conversion into JSON format? Considering HTML does not have built-in Array support, what alternative method should be used? In each row, there are 2 text fields and 1 select dropdow ...

Limit the y-axis on CanvasJS visualization

Is it possible to adjust the minimum and maximum values on the y-axis of the graph below: new CanvasJS.Chart(this.chartDivId, { zoomEnabled: true, //Interactive viewing: false for better performance animatio ...

Using JQuery to locate radio buttons that have been selected based on a variable

In my JavaScript code, I have created a variable called "thisRadio" to represent a dynamically generated div containing multiple radio buttons. Currently, one of these radio buttons may be checked and my goal is to find the checked radio button within this ...