Develop a dedicated CSS rule or stylesheet for a single embedded image before returning to the initial CSS file

I have several images on a page utilizing basiclightbox. (which is truly fantastic)

The sizes of the images are set in the "basiclightbox.min.css" file.

Below is the content of the file with the specific line highlighted:

.basicLightbox{position:fixed;display:flex;justify-content:left;align-items:center;top:0;left:0;width:100%;height:100vh;background:#999999;opacity:.01;transition:opacity .4s ease;z-index:1000;will-change:opacity}.basicLightbox--visible{opacity:1}.basicLightbox__placeholder{max-width:100%;transform:scale(.9);transition:transform .4s ease;z-index:1;will-change:transform}.basicLightbox__placeholder>iframe:first-child:last-child,.basicLightbox__placeholder>img:first-child:last-child,.basicLightbox__placeholder>video:first-child:last-child

{display:block;position:absolute;top:0;right:0;bottom:0;left:0;
margin:auto;
max-width:75%;
max-height:50%}

.basicLightbox__placeholder>iframe:first-child:last-child,.basicLightbox__placeholder>video:first-child:last-child{pointer-events:auto}.basicLightbox__placeholder>img:first-child:last-child,.basicLightbox__placeholder>video:first-child:last-child{width:auto;height:auto}.basicLightbox--iframe .basicLightbox__placeholder,.basicLightbox--img .basicLightbox__placeholder,.basicLightbox--video .basicLightbox__placeholder{width:100%;height:100%;pointer-events:none}.basicLightbox--visible .basicLightbox__placeholder{transform:scale(1)}

By adjusting the "max-height:50%" value, you can change the size of the image up to the "max-width:75%". I want to modify the 50% to 75% for particular images that are too narrow and need to be taller.

To accomplish this, I created a second css file named "basiclightbox02.min.css"

This file contains only the relevant line:

{display:block;position:absolute;top:0;right:0;bottom:0;left:0;
margin:auto;
max-width:75%;
max-height:75%}

The page structure includes:

<button class="image1001">mom</button>      
<button class="image1002">dad</button>

In the script section:

document.querySelector('button.image1001').onclick = () => {
    basicLightbox.create(`

        <img src="images/mom.jpg">
    
`).show()
}

document.querySelector('button.image1002').onclick = () => {
    basicLightbox.create(`

        <img src="images/dad.jpg">
    
`).show()
}

Also added basicLightbox.min.js.

For the full basiclightbox setup and demonstration, visit codepen:

https://codepen.io/electerious/pen/rLBvGz

There's usually advice against inline styling, but I struggled to make it work otherwise. Although if feasible, it could simplify the process.

Attempts to overwrite the original CSS values with height and width attributes were unsuccessful.

<img width="75%" height="75%" src="images/dad.jpg">

and

<img width="1400" height="900" src="images/dad.jpg">

Unfortunately, this did not reflect in the lightbox display.

I searched for ways to apply a different stylesheet to specific HTML elements but couldn't find a working solution.

Now I'm faced with the challenge of altering the size of "dad.jpg" and other images using a secondary CSS file only when necessary.

The original CSS would affect "mom.jpg", then the second CSS would target "dad.jpg", after which the first CSS would resume for subsequent images.

I believe creating a third CSS file with the initial line would help revert the precedence back.

{display:block;position:absolute;top:0;right:0;bottom:0;left:0;
margin:auto;
max-width:75%;
max-height:50%}

Though this approach seems viable, I am unsure how to write the original code that switches the line back and forth. While I excel at copying and pasting, coding from scratch in such scenarios still poses a challenge.

Here's a link to a codepen demonstrating the layout:

https://codepen.io/koretech/pen/jOpPVmg

You can also view the setup and demonstration on my test server:

Thank you all in advance, and have a wonderful year ahead!

Answer №1

From my understanding:

  • You have identified the image that needs to have a maximum height of 75% and another image at 50%
  • You are already selecting the image and opening the lightbox with it

Therefore, if "dad" is the image set at 75%, when you write:

document.querySelector('button.image1002').onclick = () => {
    basicLightbox.create(`
        <img src="images/dad.jpg">
    `).show()
}

In basiclightbox, there are callbacks like "onshow" mentioned in the documentation (https://github.com/electerious/basicLightbox)

So when the lightbox is "shown", you can select your basiclightbox and change the max-height like this:

document.querySelector('basicLightbox').style.maxHeight = '75%';

Answer №2

Consider implementing a setup like the following. (Referenced from )

let pictures = [{
    src: "https://s-i.huffpost.com/gen/1503368/images/o-SNOWFALL-facebook.jpg",
    caption: "winter",
    class: "narrow"
  },
  {
    src: "https://getwallpapers.com/wallpaper/full/4/c/3/911916-cool-beautiful-summer-backgrounds-1920x1080-notebook.jpg",
    caption: "summer",
    class: "wide"
  },
];

const instance = basicLightbox.create('', {
  className: 'lightbox',
});

const element = instance.element();

document.getElementById('showGallery').addEventListener('click', (event) => {
  instance.show();
  displayImage(0);
});

function displayImage(index) {
  index = (index + pictures.length) % pictures.length; // looping through images
  let content = '';
  let image = pictures[index];
  content += `
    <button data-next="${index-1}" class="gallery-arrow gallery-arrow-prev" onclick="displayImage(${index-1})">«</button>
    <figure id="lightboxContent" class="lightbox-figure">
      <img class="lightbox-img ${image.class}" src="${image.src}">
      <figcaption>${image.caption}</figcaption>
    </figure>
    <button data-next="${index+1}" class="gallery-arrow gallery-arrow-next" onclick="displayImage(${index+1})">»</button>
  `;
  element.innerHTML = content;
  instance.show();
}
.narrow {
  max-width: 50%;
  max-height: 50%;
}
.wide {
  max-width: 80%;
  max-height: 80%;
}
figure {
  text-align: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/basicLightbox/5.0.0/basicLightbox.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/basicLightbox/5.0.0/basicLightbox.min.js"></script>

<button type="button" id="showGallery">Show Gallery</button>

Adjusted based on OP's feedback

const instance = basicLightbox.create('', {
  className: 'lightbox',
});

const element = instance.element();

element.addEventListener("click", (event) => {
  instance.close();
});

Array.from(document.getElementsByClassName('image-btn')).forEach(imageBtn => imageBtn.addEventListener('click', (event) => {
  instance.show();
  displayImage(imageBtn.dataset);
}));

Array.from(document.getElementsByClassName('words-btn')).forEach(imageBtn => imageBtn.addEventListener('click', (event) => {
  instance.show();
  displayWords(imageBtn.dataset);
}));

function displayImage(data) {
  element.innerHTML = `
    <figure id="lightboxContent" class="lightbox-figure">
      <img class="lightbox-img ${data.class}" src="${data.src}">
      <figcaption>${data.caption}</figcaption>
    </figure>
  `;
  instance.show();
}

function displayWords(data) {
  let liHtml = "";
  let words = JSON.parse(data.words);
  for (let i = 0; i < words.length; i++) {
    liHtml += `<li>${words[i]}</li>`;
  }
  element.innerHTML = `
    <figure id="lightboxContent" class="lightbox-figure">
      <ul class="${data.class}">${liHtml}</ul>
      <figcaption>${data.caption}</figcaption>
    </figure>
  `;
  instance.show();
}
.section {
  margin-bottom: 4rem;
}

a.image-btn {
  text-decoration: none;
}

a.words-btn {
  display: inline-block;
  appearance: none;
  background: #2875ed;
  margin-left: .5em;
  padding: .5em 1em;
  border: none;
  color: white;
  font: inherit;
  border-radius: 3px;
  cursor: pointer;
  outline: none;
}

a.btn img {
  max-width: 10rem;
  cursor: hand;
}

.narrow {
  max-width: 50%;
  max-height: 50%;
}

.wide {
  max-width: 80%;
  max-height: 80%;
}

figure {
  text-align: center;
  color: white;
}

figcaption {
  font-weight: bold;
}
figure ul {
  text-align: left;
  border: 1px solid #eeeeee;
  padding: 2rem 3rem;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/basicLightbox/5.0.0/basicLightbox.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/basicLightbox/5.0.0/basicLightbox.min.js"></script>

<div class="section">
  <a href="#" class="image-btn btn" data-caption="Winter" data-src="https://s-i.huffpost.com/gen/1503368/images/o-SNOWFALL-facebook.jpg" data-class="narrow">
    <img src="https://s-i.huffpost.com/gen/1503368/images/o-SNOWFALL-facebook.jpg" />
  </a>
  <a href="#" class="words-btn btn" data-caption="Winter Words" data-words='["Something about winter", "Another thing about winter", "Another thing about how beautiful winter is", "etc."]' data-class="narrow">    Words
  </a>
</div>

<div class="section">
  <a href="#" class="image-btn btn" data-caption="Summer" data-src="https://getwallpapers.com/wallpaper/full/4/c/3/911916-cool-beautiful-summer-backgrounds-1920x1080-notebook.jpg" data-class="wide">
    <img src="https://getwallpapers.com/wallpaper/full/4/c/3/911916-cool-beautiful-summer-backgrounds-1920x1080-notebook.jpg" />
  </a>
  <a href="#" class="words-btn btn" data-caption="Summer Words" data-words='["Something about summer", "Another thing about summer", "Another thing about how beautiful summer is", "etc."]' data-class="wide">    Words
  </a>
</div>

Answer №3

Resolution:

In CSS:

.modal__container>img.higher:first-child:last-child {max-height:70%}

In JavaScript:

<img src="images/mom.jpg" class="higher">

Appreciate everyone's input.

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 could be the reason for the failure of IWSTrustChannelContract.Issue?

When using WSTrustChannelFactory with the IWSTrustChannelContract.Issue command to verify a username/password combination against an "adfs/services/trust/13/usernamemixed" URL, the validation process is successful on certain workstations but fails on oth ...

Angular MSAL Azure AD Dotnet Core Web API facing Cross-Origin Resource Sharing (CORS) challenge

I've been following along with this tutorial: https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi The authentication is working correctly. However, I'm encountering a CORS exception in the console: Cross-Orig ...

When the ID and anchor link within a URL fail to scroll to the specified anchor location

I'm trying to add an id to a URL and scroll to an anchor link <a name="tags" id='tags'></a> <a href="edit.php?id=382#tags">GO</a> I have also attempted the following: <a href="edit.php?id=382&#tags">GO& ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

Struggling to locate the distinctive XPath for the button

I am facing a situation where the XPath is non-unique and identifies 3 elements on the page that change positions upon refresh: <div class="col-xs-12 Hover"> <button data-testid="continueCheckoutButton" ng- class="continueDellMetricsC ...

Troubleshooting: Issues with Integrating Javascript and CSS into

I'm still new to this platform, so please correct me if I make any mistakes. My goal is to create a "task table" that allows users to edit existing tasks and add new ones. Thanks to the base template provided by Ash Blue, I've managed to program ...

Guide on utilizing the History API or history.js to dynamically update the "active" link based on page refreshes and back button presses

Highlighted active links using JS on my website. <script type="text/javascript> $(document).ready(function(){ $("a.nav1").click(function() { $(".active").removeClass("active"); $(this).addClass("active"); ...

What are the steps to modify the text color in WKWebView?

I've customized my ViewController to include a WKWebView, where I load my content from both .html and .css files. The result resembles a controller for reading books within the Apple Books app. do { guard let filePath = Bundle.main.path(fo ...

The HTML container expands in height with each adjustment of the window size

I am working on a simple three.js scene within a canvas element, and I want it to adjust dynamically upon window resize events. Specifically, I want the width of the canvas to change while keeping the height constant. Usually, I use window.innerWidth and ...

HTML Scroll Blocking

Recently, I have been working on designing the mobile version of a website. However, I noticed that when I try to scroll quickly on my phone, the scrolling gets interrupted and I have to wait for it to catch up. I am using the fullpage.js library in this ...

Is it possible to dynamically update the contents of a modal body and modal footer using

I'm dealing with a modal that dynamically populates two sections: modal-body and modal-footer. However, the issue is that only the content of modal-body changes dynamically while modal-footer remains static. Here's an example of the HTML code (w ...

Hover effect on Angular Material Stepper

Is there a way to apply CSS styles to a specific step (Angular material stepper) when hovering over it? I have attempted to set the styles on the elements .mat-step-header and mat-step, as well as applying a custom CSS class, but so far nothing has seeme ...

I aim to display an image with fixed dimensions, unaffected by varying screen resolutions

When monitor resolutions are altered, images may appear in varying sizes even if they are coded with metric values such as cm or mm. Is there a way to maintain the exact size of images displayed on monitors? ...

Sliding background in a multi-column accordion

I've hit a roadblock with this project. I'm working on setting up a FAQ section that needs to display its items in two columns on desktop, each with a drop shadow effect using Bootstrap 4. I've experimented with Flexbox and CSS columns with ...

What are the steps for implementing the Reverse functionality of a Stack?

I'm looking for a way to reverse the order of a Stack by leveraging the Reverse method. Currently, my attempt at using the method is not yielding the desired results: Dim StackObject As New Stack(Of String) StackObject.Push("S") StackObj ...

Exploring the Influence of Auto-Generated LINQ Queries in EF 4.2

According to an article in MSDN magazine, the June CTP now includes a feature called Auto-Compiled LINQ Queries. This feature automatically compiles and stores every LINQ to Entities query you execute in the EF query cache. When you run the query again, th ...

How to use the zip iterable to create multiple rows in a table using ReactJS

I have a collection of arrays that I need to unpack and insert into a table. For instance, I will have an array named a=[1,2,3,4] and b=['a','b','c','d'], both with the same length. Initially, I have a table with o ...

Having trouble making class changes with ng-class

I am attempting to change the direction of the arrow in my checkbox by utilizing two classes with the assistance of ng-class. Unfortunately, it is not producing the desired outcome. Below is my code: Note: The angularJS CDN has already been incorporated. ...

If the URL matches a specific path, then append a parameter

I've created a script that adds a parameter to a URL based on specific subfolders. For example, if the URL contains /de, it will add ?_sft_language=german. However, I'm encountering an issue where the code is running multiple times instead of jus ...

Exploring the possibilities in Bootstrap 5.3: Modifying the maximum width of an individual tooltip

Is there a way to modify the maximum width of a specific Bootstrap Tooltip without affecting the others? I do not utilize Sass or SCSS, and have attempted various methods outlined in the documentation: tooltip-max-width="300px" bs-tooltip-max-wid ...