Prevent Image Distortion in HTML and CSS

Is there a way to prevent a background image from stretching in html/css?

Take a look at the current code below, where the image behind a button appears like this:

#backImage6{
            /*@editable*/background-image:url(https://images.unsplash.com/photo-1598257006626-48b0c252070d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80);
            /*@editable*/background-repeat:no-repeat;
            /*@editable*/background-position:top center;
            /*@editable*/background-size:auto 100%;
        }

https://i.stack.imgur.com/kBcDA.png

If I adjust the background size to 100% 100%, then it looks like this:

https://i.stack.imgur.com/4p7Jv.jpg

HTML:

      <tr mc:repeatable="content" mc:variant="Image with CTA" id="backImage6">
        <td height="250">
          <table align="center" border="0" cellpadding="0" cellspacing="0" class="center-on-narrow" role="presentation" style="display:table !important;" mc:edit="imagewithcta">
            <tr>
              <td class="button-td">
                <a class="button-a sans text-white" href="*|ARCHIVE3|*">
                  <span class="button-link">
                    READ MORE
                  </span>
                </a>
              </td>
            </tr>
          </table>
        </td>
      </tr>

Answer №1

One way to insert an image in a div and ensure it fits horizontally is by using object-fit: cover; instead of relying solely on background-image.

#backImage6 {
  /*@editable*/
  background-image: url(https://images.unsplash.com/photo-1598257006626-48b0c252070d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80);
  /*@editable*/
  background-repeat: no-repeat;
  /*@editable*/
  background-position: top center;
  /*@editable*/
  background-size: auto 100%;
  height: 250px;
}

.image-container {
  height: 250px;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div id="backImage6"></div>
<div class="image-container">
  <img
    src="https://images.unsplash.com/photo-1598257006626-48b0c252070d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80"
    alt=""
  />
</div>

Answer №2

To ensure the background size is contained, simply set it to "contain". Your code should look similar to the following:

#backImage6{
        /*@editable*/background-image:url(https://images.unsplash.com/photo-1598257006626-48b0c252070d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80);
        /*@editable*/background-repeat:no-repeat;
        /*@editable*/background-position:top center;
        /*@editable*/background-size: contain;
    }

The background-size property set to "contain" will scale the image to fit within its container without any cropping or stretching. For further details, check out this resource: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

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

Choose the div element that is immediately before the current div

Attempting to create a harmonica effect by adjusting the height of divs upon hovering over another. The HTML is structured as follows: <html><body> <div class="section1"></div> <div class="section2"></div> <di ...

What is the best way to highlight titles that are unique but still prominent?

.test{ display:none; } .title:nth-child(odd){ background: #ddd; } <div class='title'>lorem</div> <div class='title'>lorem</div> <div class='title test'>lorem</div> <div class='tit ...

Submitting a form into a database with the help of AJAX within a looping structure

Trying to input values into the database using AJAX. The rows are generated in a loop from the database, with each row containing a button column. Clicking on the button submits the values to the database successfully. The issue is that it only inserts va ...

Encountering Problem Importing HTML Table Data into R

I am looking to import the data table located at the bottom of a specific webpage into R, either as a dataframe or table. The webpage in question is . Initially, I attempted to utilize the readHTMLTable function from the XML package: library(XML) url <- ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

The height of the absolute div tag does not match the height of the parent div

I am currently designing an editor that requires a line-number bar (gutter) on the left side. I have set a div with a height of 100% and its parent div with overflow: auto. My expectation is that if the content exceeds the given height, the editor-body sh ...

Encountering [Object Object] within an angular2 app

https://i.stack.imgur.com/iceKH.pngI recently created an angular2 application using ngrx/effects for handling http calls. My reference point was an application on GitHub. However, I am facing an issue where the response from the HTTP call is not displaying ...

When the user hits the enter key, automatically submit a form without the need for

Is it possible to submit a form on enter using type="button"? Here are my input fields: <input type="text" id = "login-user" class="form-control log-input" placeholder="Username" required="required"> <input type="password" id="login-password" clas ...

Creating a JavaScript function that responds to multiple click events

Can someone please help me out? I have the link to the output of my work below using JavaScript and HTML: My goal is for only one circle to be active when clicked, while the others are disabled. Currently, when I click on a circle and then another one, bo ...

Difficulty encountered while using MySQL column update button

I'm looking for assistance in updating my database using an SQL statement after a button is clicked on the website. I attempted something but it was unsuccessful. Could anyone provide guidance? Here's the code snippet: http://pastebin.com/D0S83Jg ...

Selecting a folder path with Angular 6: A step-by-step guide

Currently, I am aiming to extract the folder path string without uploading any files. The goal is simply to capture the path for future use. Below is an example of how you can prompt users to select a file: <input id="folder-input" #folderRef type="fil ...

Navigating a roster of users in JavaScript

I'm dealing with a collection of user data stored in an array accountsade: [ { id: 0.4387810413935975, name: "Adrian", password: "345", userName: "nathanael" }, { id: 0. ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...

Is there a way to extract the text that is displayed when I hover over a specific element?

When I hover over a product on the e-commerce webpage (), the color name is displayed. I was able to determine the new line in the HTML code that appears when hovering, but I'm unsure how to extract the text ('NAVY'). <div class="ui ...

Issues arising with transferring information between components

My webpage had a header with a search engine input, a list of posts, and pagination all on one page. I made the decision to separate the header into its own component in a different Vue file. However, after making this change, searching for posts by their ...

The JS copy function is successful when operating on a single element, but it encounters issues when attempting to run on multiple elements, only copying

My code includes a copy function that copies the data from a textarea to the clipboard when a button is clicked. The functionality works perfectly for the first textarea, but for subsequent textareas, the buttons do not perform the copy action. Check out ...

To add a code snippet to the right side of a paragraph using CSS, place it at the end of the

Is there a way to insert code at the end of each paragraph and have it aligned to the right on the same line as the last sentence? Update: I initially tried using float:right, but encountered an issue with vertically aligning the code with the last line ...

What is the reason behind the modification in flex item size when align-items property is applied?

When creating the responsive design, I utilized flexbox. Surprisingly, without changing the size of each flex-item, applying align-items:center caused the size of the first flex item (PICTURE 2) to change when displayed in a vertical view. On the other han ...

Guide to highlighting rows in v-data-table with a click in Vuetify (version >= 2.0)

In my email management system, I utilize a v-data-table to organize emails. When a user clicks on a row, a popup displaying the email details appears. Desired Feature: I am looking to have the rows marked as "readed" (either bold or not bold) after th ...

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...