Utilizing the background-size property for image styling within the img tag

html

<div>
<img src="http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg" />
</div>

css

div{
    width: 200px;
    height: 100px;
    background-color: red;
}
img{
    position: relative;
    width: 100%;
    height: 100%;
    background-size: cover;

}

Why isn't the background-size: cover property working in this scenario? It should be supported in CSS3, but it's not having an effect. Is there a way to prevent the image from stretching?

We can achieve a similar effect using

background: url("http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg") no-repeat; background-size: cover;
instead.

Answer №1

Method #1 - Utilizing the innovative object-fit property (Browser support)

To effortlessly achieve desired results, simply apply object-fit: cover; to the img element.

img {
  display: block;
  width: 200px;
  height: 100px;
  object-fit: cover;
}
<img src="http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg" />

Dive deeper into this latest property by checking out the informative webplatform article.

An excerpt from the mentioned article - explaining the 'cover' value:

The entire image is resized to fit perfectly in the box while preserving its aspect ratio. This usually leads to only a portion of the image being visible.

Furthermore, explore this fiddle related to the aforementioned article showcasing all possible values of the object-fit property.

Method #2 - Substituting the img with a background image via css

img {
  position: relative;
  width: 0;
  height: 0;
  padding: 50px 100px;
  background: url(http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg) no-repeat;
  background-size: cover;
}
<img src="http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg" />

Answer №2

See how easy it is to accomplish with jQuery!

var imgSrc=$('figure img').attr('src');

$('figure img').remove();
$('figure').html('<figure class="background-image"></figure>');
$('.background-image').css('background-image', 'url(' + imgSrc + ')');
$('.background-image').css('background-repeat','no-repeat');
$('.background-image').css('background-size','cover');
$('.background-image').css('width','100%');
$('.background-image').css('height','100%');

check out the demo here

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

Error encountered: SyntaxError - Missing semicolon before statement in AJAX call while processing JSON data

I am currently in the process of making a cross domain JSONP call utilizing this code snippet: jQuery.ajax({ async: true, url: 'http://mnews.hostoi.com/test.json', dataType: 'jsonp', method: "GET&quo ...

Increase and decrease a counter in Javascript by clicking on two separate image tags, with increments and decrements between 1 and 10

Hello! I really appreciate your help. I am currently facing the following issue: <div id="thumb1"> <img class="img-responsive" id="prova" src="img/thumb-up-dark.png" alt=""> <div id="pinline">0</div> ...

AngularJS failing to execute Ajax request

I've been working on implementing an Ajax call in a controller to retrieve a list of all the students, but I'm having trouble getting it to work when clicking a button. Here is the code that I've written - can anyone help? module.controll ...

Animating with jQuery to a specific offset or position

Currently, I am utilizing jQuery animate to modify the location of an element: $('#item').animate({'top' : '-50'}, 0); The goal is to set the position without any animations. I experimented with both offset and position, but ...

Lists are not limited to only <li> elements and elements that support scripts (<script> and <template>)

While testing my webpage's accessibility in Google Chrome Lighthouse, I encountered the following error. I am aware of the significance of properly structured lists in enhancing webpage accessibility. It is perplexing for me to receive this error desp ...

Tips on enhancing Ajax requests with jQuery and deferred objects

Currently, I have implemented four or more ajax rest calls within the $(document).ready(function(){} function. To handle this situation, I resorted to adding .done() to the largest call as a temporary solution. While it is "working," I am looking to enha ...

Querying MYSQL database using PHP and JQuery

I currently have a gallery of images where the results are limited to 10. My goal is to use jQuery to load the next 10 rows (images) from the database when the 'Load more Results' button is clicked. Right now, I utilize a class called query.php ...

Increase the identification of HTML element with jQuery

I've encountered an issue while trying to increment the id of 2 HTML elements, hwAddition and itemNumber, upon a button click event. The HTML code in question is as follows: <div id="hwAddition"> <div id="itemNumber" s ...

What is the reason for JavaScript consistently returning the initial value as the result?

My current issue involves customizing Joomla article content using a module. I am attempting to hide a div until a user clicks on an input, such as a radio button labeled Test1. Once Test1 is selected, another hidden field within the div should display the ...

Organizing a list based on Date property in C# versus implementing jQuery for the task

Currently, I am working with a List<Event>. Each Event object contains a Date property. I have successfully bound this list to an asp:repeater, resulting in a simple list of event titles that look like: event 1 event 2 event 3 event 4 event ...

Animating background color with jQuery when the page loads

I am facing a challenge that seems simple yet tricky - I want to apply my hover effect on page load. My navigation system consists of div boxes, with jQuery code to animate their background color on hover: <script type="text/javascript" src="http://jq ...

Ways to retrieve several parameters from a controller using Ajax Jquery in Codeigniter

I need to retrieve a list of images from a folder based on a specific ID. Currently, I am able to get the file names but I also require the upload path. Is there a way to obtain both sets of data using a single function? Javascript Code: listFilesOnServ ...

Which option is more effective: using an id or using !important?

While some say to avoid using the !important rule and others argue that since ids are unique, there is no need to target like #main > #child and you can simply use #child. In my particular case: #main > div{ color: red; } #child{ color: blue;/ ...

Angular2 data binding does not update when properties change

I'm struggling to establish the connection between the fields and the component in order for them to update when the properties change in OnDataUpdate(). The field "OtherValue" successfully binds two ways with the input field, and the "Name" field di ...

Issue with AJAX POST request not retrieving data from PHP MySQL database using AJAX

I am facing an issue where the post data is not passing to get-data.php while trying to retrieve data from the database using ajax to insert it into another element. Any thoughts on what might be causing this problem and possible solutions? https://i.stack ...

Exploring the possibilities of integrating jQuery into Firefox extensions

Can someone provide guidance on effectively implementing jQuery within a Firefox extension? My research has not yielded any up-to-date methods that address the latest version of jQuery, and I am aware that directly including it via script tag may lead to c ...

Modify the collapse orientation in Bootstrap

I would like the button to expand from the bottom when clicked and collapse back down, instead of behaving like a dropdown. <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

How to eliminate excess white space on the right side in Bootstrap 4

Could someone please clarify why I am experiencing a white space on the right side when using Bootstrap 4? This is the primary code block for the page. <main id="intro" role="intro" class="inner text-center"> <h2>Lorem Ipsum</h2> ...

Grid system that is responsive, while also maintaining a fixed column width

My problem seems simple, but I can't find an easy solution. What I need is to create a grid with fixed widths and a fixed distance between each column. Each column should be 400px wide, and as the browser window is resized, the grid should adjust by ...

Storing multiple values in local storage

Hey there! I have a text box where I input grades, and they get saved in local storage. I can see them below the text box. Now, I want to add more text boxes for additional grades. How can I achieve this and ensure that the grades are saved in a separate a ...