Inject EJS Template String into Express CSS File to Customize Background Image of an HTML Element

I have successfully configured a css file for my Express ejs web app. All the styles are displaying correctly, paths are accurate, and everything is working perfectly.

Within one of my ejs files, the structure looks like this:

<%- include ("partials/header") %>
<img src= <%= project.image1 %> width="300px">
<%- include ("partials/footer") %>

The image linked to by project.image1 is appearing as expected.

My question is, can I use the following code in my css file:

.class {
background-image: url("<%= project.image1 %>");
}

After doing some research on similar questions, it seems that none of them directly address my specific inquiry.

Answer №1

A common issue encountered is that the style tag works within the same file, but not with the link style. To illustrate this, consider the following code snippet:

server.js

const express = require('express');
const path = require('path');

const app = express();

app.set('view engine', 'ejs');

app.set('views', path.join(__dirname, '/views'));

let image = 'https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg';

app.get('/', (req, res) => {

  res.render('home', { image } );
})

app.listen(3000, () => console.log('Server is up on port 3000'));

The above code serves as a simple example of a server using Express.

home.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <!-- Using a link to an external stylesheet does not work -->
  <link rel="stylesheet" href="style.css">

  <!-- Only inline styles seem to be effective -->
  <style>
    .my-background {
      width: 100%;
      height: 200px;
      /* This references the ejs variable 'image' */
      background-image: url('<%= image %>');
      background-repeat: repeat;
      background-size: 100px;
      background-position: left;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1>Hello World</h1>
  <div class="my-background"></div>
</body>
</html>

This explanation should provide clarity on the matter.

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

Encountering a Parse Error with Less CSS triggers an error message for unrecognized input specifically related to background properties

I am struggling to identify the issue with my CSS while using the LESS CSS library. After running my site with LESS, I encountered an error. However, upon examination, the CSS appears to be valid. Can someone please point out what could be wrong with my C ...

Adjust the appearance depending on the React state variable

I am trying to add animation to a search icon when clicked in React. Using the useRef hook, I am able to access the element and applying custom styles to it. const [searchBar, setSearchBar ] = useState(false); const searchIcon = useRef(); const searchIconS ...

Embracing the power of Typescript with Node and Express?

While trying out the TypeScript Node Starter project from Microsoft, I found myself intrigued. Is it really possible to use TypeScript instead of Node on the server? There are a number of server-side tasks where TypeScript excels: - Building a web API ser ...

Why do I continue to receive the error message "Cannot POST"?

I've been struggling with setting up a basic HTML form and an Express server. No matter what I do, the routing just doesn't seem to work. Every time I try to post something, I keep getting a "Cannot Post" error message. What am I doing wrong? ...

Tips on displaying just two buttons in one line

When using *ngFor to display multiple buttons, all buttons appear in one column. I want to have only 2 buttons in a row: the green buttons in one line, and the red buttons in the next line. How can I achieve this? Here is what I have tried: <div class= ...

Styling <html:link> elements with CSS

I'm new to using struts and I'm struggling with applying my CSS styles to link tags. <html:link action="LoginLink" styleClass="loginButton"/> My goal is to add a button image to a link that directs to a login page. I've successfully ...

Assistance needed for Internet Explorer

When I designed a webpage in Firefox, everything looked great. However, when I opened it in Internet Explorer and resized the window to less than maximum size, half of the main div disappeared under the footer. If you want to see the issue for yourself, v ...

html how to delete the beginning and end of hr element

There is a <hr noshade> tag in my HTML code which does not have any effect on the web view. However, when I print it to a PDF file, it shows head and tail like this: https://i.stack.imgur.com/TaBAc.jpg Here is my CSS that applies styling when print ...

Tips for wrapping a div element around another div at the top left corner

I am working with a particular layout. <div class="comment"> <div class="leftpart"> </div> <div class="rightpart"> </div> </div> When viewing on a desktop, I maintain the original styling where each div is in its own s ...

Syntax error in node/express: missing closing parenthesis after argument list

Just starting out with Node.js... const express = require('express'); const bodyParser= require('body-parser'); const MongoClient = require('mongodb').MongoClient; const app = express(); app.use(bodyParser.urlencoded({extend ...

Adjust the parent element to match the width of the child by utilizing the "display: grid" property

edit: I'm uncertain if this is a duplicate issue. My concern is not about the background color extending beyond the container width, but rather about expanding the container to match the size of its child with display: grid. I have updated the example ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

How to extract URL parameters in an Express.js and AngularJS web app

Encountering a routing issue in my ExpressJS and AngularJS project. This project is not a single-page application, and we are not utilizing any view engines like jade - only plain HTML. I am currently working on implementing password reset functionality ...

Collapse or display div elements with jQuery - First close all other elements before opening the selected item

The Problem at Hand Currently, the script is expected to hide all elements with the "gallery-collapse" class and reveal the specific content based on the clicked link. However, sometimes multiple divs might appear simultaneously when switching between ite ...

What is the best way to align and adjust the position?

I'm attempting to attach a button to a page. I may not be an expert, but here's what I have so far: body { width:100%; height:100%; background:#181516; overflow:hidden; position:absolute; } .bg { background:url(../im ...

Changing the Appearance of the RStudio Editor

I am exploring options to customize an RStudio Editor Theme to personalize the colors. My current setup includes RStudio version 0.99.473 on Windows 10. After reviewing Any way to change colors in Rstudio to something other than default options?, which wa ...

Unable to set width for td element in media query is not functioning as expected

Is there a way to adjust the width of td elements for smaller screens within an email template? I have tried setting the style as important, but it doesn't seem to be working. CSS .alignmentColumn { width: 25% !important; //for desktop @med ...

Is there a way for me to determine if a user has engaged with a form?

I'm surprised by how difficult it was to find information on this topic through Google. Currently, my struggle lies in wanting my form fields to change color based on validity only after the user has interacted with the form. I don't want invali ...

How to design <p> elements inside a bordered container?

I am currently working on a webpage that features text enclosed in bordered boxes with styled formatting. The primary issue I am encountering is that when I try to add another paragraph within the styled <p> tag containing the border styling, the su ...

Create PDF files on-the-fly using the html-pdf module

Recently, I've been using the npm package html-pdf for generating PDF invoices dynamically. However, I encountered a problem where instead of saving values to the PDF file, it was saving ejs code. Does anyone have any insight on why this might be happ ...