Maintain image proportions in CSS while rendering

Let's solve a simple CSS challenge:

  • Your task is to display animal pictures in the grey box as seen in the example below
  • The image size should be 150x150 pixels
  • Keep in mind that the aspect ratio of the image must be maintained, so not all of it will fit into the square
  • Since most images will exceed the allowed 150x150 dimensions, we want to focus on displaying the middle part of the image

Here is some HTML code:

<div class="gallery-item" style="height: 232px;">
                    <img src="/media/animals/images/african-buffalo.jpg" alt="African Buffalo ">

                    <div class="gallery-item-caption">
                        <a href="/animals/african-buffalo" title="African Buffalo ">African Buffalo </a>
                    </div>
</div>

And here is some CSS code:

.gallery-item {
float: left;
padding: 15px;
margin: 15px;
background-color: #ececec;
}

Take a look at the result:

Answer №1

If you're struggling with wide images not fitting well in a square, consider using the background-image property on divs instead of img. You can also use background-size:cover for a better fit. This idea was inspired by a discussion on this forum, with a live example available here.

CSS

.gallery-item{
    width:50px;
    height:50px;
    border:solid 1px #000;
    margin:10px;
    background:url('http://lorempixel.com/100/200') center center no-repeat;
    background-size:100%;
}

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

The float:left property within a div is not behaving as anticipated

I am having trouble positioning my second div. In order to have 70% of my website for posts and 30% for a small text display, I created a new div. I believe the correct way to position it is by using "float: left" so that the div goes under the banner whe ...

Carousel malfunctioning, refusing to slide smoothly

I recently copied the bootstrap 5 Carousel code and tweaked it with some additions, however, it's not functioning correctly. It seems to only go to the 2nd slide and then stops. Strangely enough, when I open the developer tools (F12) and go to inspect ...

Is it possible to confine CSS keyframe animations within a specific scope?

Is it feasible to limit keyframe animations to a specific scope defined by classnames? This could make it easier to reuse the same animation names without any conflicts. I couldn't locate any information on this topic. If restricting keyframe animati ...

Looking to troubleshoot a white background issue while attempting to create a transparent navbar

I am trying to create a full-page landing with a transparent navbar using bootstrap4. My goal is to have a sticky navbar that remains at the top as the user scrolls down the page. When I apply the class 'fixed-top', the navbar stays at the top b ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...

Is it possible to create a WebXR using the ARCore API specifically for IOS devices?

I'm experiencing an issue with my code that seems to be working flawlessly on Android devices, but when attempting to run it on an iOS device, clicking the button to start the AR session yields no results. I reached out to ChatGPT for assistance, and ...

securely load HTML form with data stored in MySQL

I have developed a basic HTML/JS math form for performing calculations. To simplify the form, I made it more concise for clarity: function output(){ var value1 = document.getElementById('value1').value; var ...

What about an external ui-grid-menu-button option for customizing the

Looking for a solution to separate the ui-grid-menu-button from the top right of the table and position it elsewhere? Check out this Stack Overflow question from a year ago which unfortunately remains unanswered: External ui-grid-menu-button Struggling t ...

Pass the chosen option to PHP using Ajax within the same webpage, utilizing HTML

My Goal: I am working on a HTML/PHP page that displays the home page of my website. One section on this page is dedicated to highscores, with data retrieved from a database. Users can use a Select box to choose how the highscores are sorted. View the high ...

Looking for a JavaScript or jQuery library that can effectively translate XPath into a user-friendly CSS3 format for easy selection in

Is there a way to transform an XPath expression such as /html/body/div[3]/ul/li[1]/a[5] html > body > div[3] > ul > li[1] > a[5] I am aware that CSS3 selectors do not support indexing....what alternative approach should I take? ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

Attaching a Stylesheet (CSS) without being inside the HEAD Tag

After seeing numerous inquiries about this topic, I have yet to find the answer I seek. My main question is whether it is feasible to connect an external stylesheet in a location other than the HEAD tag. I am facing this issue because I need to use Conflu ...

What is the best way to conduct a comparison between text within an HTML element and a particular value contained in an array of objects

My first attempt at creating a quiz app using JavaScript has hit a roadblock. I am facing an issue with calculating the user's score based on their selected answers and the correct ones. The userScore variable is not incrementing as expected, always s ...

Utilizing exceptions for specific objects in CSS

My table CSS includes the following code: .table-hover>tbody>tr:hover { background-color: #f36f25; color:#FFFFFF; } I am looking for a way to exclude specific rows from this hover effect. Is there a method to customize which rows trigger t ...

How can I retrieve the background and border color of the focused HTML element after pressing the tab on a website?

I am seeking to automate the process of conducting website accessibility checks by analyzing the color contrast between the focused element (after pressing tab) and its border color. Strategy: Initially, I attempted to take screenshots of the entire web ...

Adjust the A-frame's jumping height by assigning it to a variable

I'm currently working on developing a video game using Aframe, and I have a question regarding setting my jump height as a variable within the code. This is what I have so far: <a-entity id="rig" position="17.5 50.1 0&quo ...

The HTML button remains hidden behind a Three.js background until I bring up the Dev Tools

As I dive into my university assignment, creating a 3D scene with Three.js is both challenging and exciting. One specific requirement is to add a button that triggers the movement of one of my three vehicle objects. However, an issue arises as I can' ...

Updating the appearance of tooltips in Bootstrap 4 with custom CSS styles

I am trying to customize the tooltip style by changing the background color to white. I have used the following CSS code: HTML code: <th rowspan="2" style="text-align: center">Test <sup><img src="assets/icons/help.p ...

What are the best ways to engage with a div element using keyboard shortcuts?

Is it possible to enable keyboard shortcuts for interacting with div elements? I am working on a project tailored for seniors who may have difficulty using a mouse. Is there a way to utilize keyboard shortcuts to click on divs and access their contents? H ...

The header menu is not appearing on the gray bar in Internet Explorer

Having some issues with IE8, specifically on the website . The website header is not displaying correctly in IE8, but it works fine in Chrome and Firefox. Another issue is that the white area of the site is not 960px width as intended... ...