CSS - Choosing between Background Size Contain or Default Size

Is there a solution to my dilemma regarding background images in a div? I need the image to be contained within the div if it's larger (background-size:contain;), but if the image is smaller, I want to keep it as is without stretching or blurring (background-size:auto;)

I am using a WordPress website, so I don't have control over the images in the long run, as they may change without needing a programmer's intervention. Is there a way to achieve this effect?

Answer №1

  window.onload = function() {

    var imageSource = document
                    .getElementsByClassName('foo')
                     .style
                      .backgroundImage
                       .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
                        .split(',')[0];

   
    var divWidth = imageSource.offsetWidth;

    var newImage = new Image();
    newImage.src = imageSource;

    var imageWidth = newImage.width,
        imageHeight = newImage.height;

    alert('width =' + imageWidth + ', height = ' + imageHeight)
    
    if ( imageWidth > divWidth ) {
      
        imageSource.style.backgroundSize = "contain"; 
      
    }

}

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

Replicate the cursor to make it show up twice

Is there a way to create a duplicate cursor effect on my website, making it appear twice and perhaps look like it's drunk? I want the cursor to still interact with images and change accordingly, but always have two visible. Can this be achieved easily ...

How do I position an input box at the bottom of a split window using CSS?

I am grappling with maintaining the alignment of an input box underneath a chat window while using the float:left property. As there will be multiple chat windows and I want them to remain next to each other, I am uncertain about how to achieve this. Chec ...

Ways to display one element while concealing it when another is clicked

I am utilizing a series of div elements that can be triggered with the following code snippet: $(".course_id").on("click", function(){ var id = $(this).data("id"); $("div#lessons_by_course_" + id).removeClass("hidden"); }); The ...

Tips on adjusting the size of a Materialize CSS datepicker to perfectly fit within a card

Currently, I am developing a login page in html utilizing the materialize css framework. In my design, I created a card where Login and Register are displayed as tabs within the card. However, one of the forms includes a datepicker from materialize which ...

aligning an image in the center of a webpage

I have created a simple HTML code to center an image inside the body of an HTML page. It works perfectly on Windows with various browsers, and on phones vertically when rotated. However, the issue arises when I open the site on a Mac as the centering doe ...

Embedding the scrollbar within the div container

I'm having trouble placing my vertical scrollbar inside my div and adjusting its position. To streamline the code, I have extracted a portion below: .toprightcontrols { margin: 0 3% 0 0; display: flex; position: absolute; justif ...

Ensure that the child div remains at the bottom of the parent div

I'm trying to make sure that the subfooter div stays at the bottom of the childbox div like a footer. You can see the code on this jsfiddle link <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title ...

Having difficulty altering the div color in real-time using VueJS

I'm currently in the process of building an application with Bootstrap and VueJS. My goal is to create a folder structure similar to Google Drive, where I want to make a div stand out in blue once it's selected. Below is the code snippet: ex ...

What is the best way to align text in the middle of a div using Foundation framework?

It seems like I may be either overanalyzing this or overlooking a small detail. The task at hand is to align text in the center within a div using Foundation. Here is the current code that I am working with: [1]<div class="row"> [2] <div class ...

Discover an effective way to display Ajax search results above a different div element!

I am having trouble with positioning my search results on top of other divs. To see the issue, you can watch the screen recording by clicking on this link: https://drive.google.com/file/d/1kU_vl2ZAmSCok0pxnTTvY hacxqcZZ9m_/view?usp=sharing These are the s ...

HTML/CSS - Troubleshooting Animation Issues

I am currently experimenting with different website animations and implementing responsive design. However, I encountered an issue when trying to apply these changes to my header, which also affects the .heading element. It seems that there is a problem w ...

Angular Material: div not being filled by layout-fill

<!-- Container Div --> <div layout-fill> <!-- Image Div --> <div layout="column" layout-align="center center" class="coverImage" layout-fill> <md-content class="md-padding"> Sample Text Here ...

Is there a way to automatically make required fields turn red upon form load using model validations in MVC?

After implementing Model validations and remote attribute validation, I noticed that all mandatory fields turn red when the submit button is clicked. Is it possible for all mandatory fields to turn red upon form load instead? ...

Best practices for arranging several divs with CSS

I am in the process of creating a main header for several web pages I'm working on. The layout I have in mind includes an image, centered text below the image (all to the left of the main header), a main header that I want to be in the center of the p ...

The spacing between images on mobile devices is excessive

My images on mobile have too much space between them: mobile version They appear fine in Dev Tools: dev tools version This is my HTML: <div class="container-fluid"> <!-- <br> --> <div class="row"> ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

Text scrolls - items are shown all at once

I've been experimenting with creating moving/scrolling text. After some trial and error, I've managed to achieve this effect. If you're interested, you can check out the code on CODEPEN. The issue that's currently bothering me is rel ...

What is the best way to target an HTML element that is only connected to a particular class?

My HTML code includes the following 3 elements: <span class="a b"></span> <span class="a"></span> <span class="a b"></span> I am trying to select the element that only has the class "a". When I use $("span.a"), it sele ...

Unexpected behavior with first-child selector in a simple CSS code

It seemed so clear to me, but it turns out I was mistaken. Check out this link $('p:first-child').css({color:'red'}); The color of all text is not being altered. <div class="post text"> <a href="#">this is a url</a> ...

Why is the div still displaying with the same id and class even after postback in a partial view using MVC?

Encountering a issue where the partial view is repeating after post back, despite the functionality working correctly. Here is the code snippet from the View: @using (Ajax.BeginForm("MarkDefiniteDischargePatient", "PDDD",new { }, new Aja ...