Ways to dynamically set a background image URL using solely HTML and CSS

I am looking for a way to dynamically assign the url of the background-image through CSS based on attributes defined in HTML tags. I have tried using both attr() and var(), but neither seem to work. I prefer not to use JavaScript as the URL may change later, requiring manual script triggering.

Is there a more effective solution to achieve this?

body {
  display: flex;
}

.normal, .attr, .var {
  flex: 1;
  height: 240px;
  border: solid 1px #666;
  background-size: cover;
}

.normal {
  background-image: url("https://picsum.photos/320/240");
}

.attr {
  background-image: url(attr(data-bg));
}

.var {
  background-image: url(var(--url));
}
<div class="normal"></div>
<div class="attr" data-bg="https://picsum.photos/320/240"></div>
<div class="var" style="--url: 'https://picsum.photos/320/240';"></div>

In addition, I would like to be able to concatenate strings if possible.

.image {
  border: solid 1px #666;
  width: 320px;
  height: 240px;
  /* I wish this is possible */
  background-image: url("http://www.example.com/images/" attr(data-bg) ".png");
}
<div class="image" data-bg="adorable_cat"></div>

Answer №1

It seems like using inline background-image property would be more convenient, especially when concatenating URL strings. Here's a simple way to achieve this:

<div class="var" style="--url: url(https://picsum.photos/320/240)"></div>

.var {
  background-image: var(--url);
}

Interestingly, the use of url(var(--url)); doesn't appear to work properly (at least in Chrome) for reasons that are unclear to me.

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

Centering an item within a dropdown navigation bar

Hey there, I'm currently facing a challenge with centering an image within my dropdown bar. My goal is to have it float to the right and be centered, but it's not cooperating. Here's the code snippet I'm working with: <!DOCTYPE htm ...

Ensuring the accuracy of input values within an MVC Pattern

I am currently struggling to use an HTML form to submit the specific URL index.php?page1&name2=value2&name3=Value3. The closest I have gotten is index.php?page1=&name2=value2... I am facing challenges in obtaining a clean page1, and I am confi ...

Updating a text input's placeholder using Bootstrap4

Bootstrap 4 provides classes like text-left and text-right for aligning text inside an input field. Is there a Bootstrap-friendly method to only align the placeholder text in an input without affecting the alignment of the actual text? ...

Learn how to easily center a responsive navbar using Twitter Bootstrap

I'm having a bit of trouble creating a website with Twitter Bootstrap, specifically when it comes to centering the navigation links in responsive design. My goal is to have a two-row navigation bar for tablet and phone devices, with the brand name at ...

The attempt to enhance the appearance of the string table has been unsuccessful

In a jQuery call, I am working with a string of HTML as shown below: var template = '<html >' + '<head>' + '<h1>Most important heading here</h1>'+ '</head>' + '<body>' ...

Why does WebView crash when I call a Java function from my Javascript code?

Here's a perplexing issue I've encountered. Whenever I call a Java function from my Javascript code, the WebView crashes. This code is directly from the official documentation. Java: public class HelloWebView extends Activity { private W ...

Automatically play the elements within a div using jQuery

I have various sections within different divs that I want to display without the need for manual clicking on tabs. While I've been able to toggle the visibility of these sections by clicking, I would prefer them to display automatically in a loop usin ...

The appearance of the website is altered when viewed on a Mac device

I recently completed a website that looks great on Firefox PC, but has some issues on Firefox Mac. When viewing the site on Mac, the background image in a specific div is not showing up. Additionally, in the footer section, elements floated to the left ar ...

Add a script tag to every image in my HTML at once using C#

Managing a site with a thousand images can be overwhelming, especially when trying to add a script tag like <%=Settings.MyDomain%> to each one. I'm looking for a more efficient way to accomplish this task without spending hours on manual labor. ...

CSS font attribute stylus variable

Can you help me troubleshoot this issue with the variable in stylus that is setting the font attribute using shorthand syntax? button-font = 100 16px Helvetica Neue', Helvetica, Arial, sans-serif I'm encountering the following error message: ...

Tips for maintaining focus while tabbing in a contenteditable field?

Why does the table lose focus every time I press tab instead of inserting a white space? How can I change this so that pressing tab just inserts a regular tab space? ...

The ng-change function is successfully executed only when the user presses the backspace key or enters

<input type="email" ng-keypress="testFunc()" ng-model="text" id="femail" class="form-control margin" name="femail" placeholder="Email*"/> <p style="color: red;">The input field has changed {{count}} times.</p> JS $scope.count = ...

Use CSS to mimic the :hover functionality for touchscreen devices

I am struggling to get this piece of code to function correctly, $(document).ready(function() { $('.hover').bind('touchstart touchend', function(e) { e.preventDefault(); $(this).toggleClass('hover_effect'); }); ...

"Fetching a textbox value and passing it into an anchor tag query string: a step-by-step

What is the best way to extract a value from an "asp:TextBox" and insert it into an anchor tag? The asp:TextBox I am working with is labeled txtTaskName. <a href='EmailManager.aspx?<%# Eval(txtTaskName.Text) %>' runat="server">Add E ...

Activate dropdown menu link when tapped twice on tablet devices

I am trying to implement a dropdown navigation link feature on tablets where the child menu div drops down only on the second click. This functionality already works on iPads, but on Android and Windows tablets, the link is triggered at the same time as th ...

Steps for importing selenium web elements:

Can all of these ... tags be extracted simultaneously? I aim to retrieve every ... from that particular webpage! Web address: 'https://school.programmers.co.kr/learn/challenges?order=recent&page=1' ...

Utilizing a variety of languages within a single HTML document

Is there a way to incorporate both Danish and Polish text in the same HTML output using PHP? I recently discovered that these two languages are encoded in different character sets. Does anyone have a solution for this? ...

What triggers the activation of the inline formatting context in this particular scenario?

MDN provides insight about the img element in regard to styling with CSS, highlighting how images interact within an inline formatting context. The positioning of images when used in-line can be affected by vertical-align: baseline due to <img> not ...

What are the reasons behind the failure of this specific <audio> example on certain web browsers?

Can anyone explain why this particular example of audio code (from W3Schools) fails on Firefox 16 and IE9, but succeeds on Chrome V24? UPDATE: <!doctype html> <audio controls> <source src="horse.ogg" type="application/x-msdownload"> ...

Ways to create a scrolling container with dynamic CSS transformations

Visit this website with a unique feature - a scrolling div on the left. The div scrolls along rhythmically as you navigate through the page, changing colors dynamically. The use of position:fixed is not the only method to achieve this effect. So, what oth ...