Maintaining the image's aspect ratio while cropping it to fit within the maximum or minimum height

Is there a way to make an image responsive by resizing it while keeping its aspect ratio intact at all sizes? I want the height of the image to stay fixed above 650px, cropping the top and bottom to maintain the ratio without stretching. Additionally, I don't want the image's height to go below 200px, only adjusting the left and right sides. The goal is for the image to always stay centered on the page. Here is my current progress: https://jsfiddle.net/4q83mh41/

<div class="hero">
<img src="http://wpdevserver.x10host.com/wp-content/themes/wp/img/hero1.jpg">
</div>


.hero {
    width: 100%;
    min-height:200px;
    max-height: 650px;
    position: relative;
}
.hero img {
    width: 100%;
    height:auto;
    min-height:200px;
    overflow: hidden;
    max-height: 650px;
    position:absolute;
}

Thank you in advance.

Answer №1

Using JavaScript, you can dynamically adjust the position of an image within the .hero div. In addition, CSS media queries can help maintain the correct width of the image.

.hero {
  width: 100%;
  overflow: hidden;
  max-height: 650px;
}

.hero img {
  position: relative;
  height: 200px;
  width: auto;
}

@media (min-width:420px) {
  .hero img {
    width: 100%;
    height: auto;
  }
}

The JavaScript code listens for resize events and modifies the top and right properties of the image to keep it centered within the relatively positioned container. JQuery is utilized for property manipulation.

var heroresize = function() {
  var aspect = 1800./858,
      maxheight = 650,
      minheight = 200,
      width = $(".hero").width();
  if(width < minheight*aspect) {
    $(".hero img").css("right",(minheight*aspect - width)/2 + "px");
  } else {
    $(".hero img").css("right","0px");
  }

  if(width > maxheight*aspect) {
    $(".hero img").css("top",(maxheight - width/aspect)/2 + "px");
  } else {
    $(".hero img").css("top","0px");
  }
}
$(function(){
  heroresize();
  // remove if you don't need dynamic resizing
  $(".hero").on("resize",heroresize);
});

Be aware that using JavaScript for resizing may result in some lag or stutter due to performance issues with resize events. If dynamic resizing is not necessary, you can remove the specified line.

You can experiment with a live version of this code on CodePen via this link: http://codepen.io/regdoug/pen/azxVwd. Please note that the CodePen example has a maximum height set at 350px for easier viewing of the effect without excessive resizing.

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

Steps for modifying the width of a horizontal line element so that it aligns with an input element

I'm attempting to dynamically adjust the hr element's length based on the length of the input element by using CSS. Additionally, I'd like to incorporate an animation that triggers when the input is focused. I came across a solution for th ...

Ensuring the same height for the navigation bar and logo with aligned vertical text

I'm in the process of recreating a simple navigation menu and I've reached the section where I am encountering an issue with the list items. The orange li element is not filling up 100% of the width, and I also need the links to align in the midd ...

Menu not functioning properly on iPhone?

I recently completed a web page that features a fixed menu at the top of the page. Strangely, while the menu works perfectly fine on the Android mobile version, it doesn't seem to function properly on an iPhone. Can anyone shed some light on why this ...

IE and Firefox both render CSS styles in their own unique ways

When viewing my website acro.batcave.net on different browsers like IE (Windows 7, IE 11.x) and FF (Windows 7, FF 37.x), I noticed that it appears differently. Chrome seems to have the same display as FF. The CSS file can be found at acro.batcave.net/css ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Testing the Limits of CSS Hover

I'm having trouble figuring out how to implement this. When hovering, a yellow square/background should appear with an offset similar to the one in the image below. I am utilizing bootstrap for this project. Any assistance or guidance would be greatl ...

Is there a way to align these side by side?

Is it a silly question? Perhaps. But I can't seem to figure out how to align my text and colorpicker on the same line instead of two. Take a look at my fiddle. I've tried removing display:block and clear:both, but that didn't do the trick. H ...

Flexbox ancestor causing Bootstrap 5 Carousel width to double

A peculiar issue arises with the Bootstrap 5 Carousel placed inside a Flexbox where it unexpectedly expands in width (pushing other flex-items aside) when transitioning between images. This behavior persists even when the immediate container is set to disp ...

Adjusting button alignment when resizing the browser

Is there a method to relocate buttons using Bootstrap 5 in HTML or CSS when the browser is resized? For instance, if the button is centered on a full-screen browser, but I want it at the bottom when resized. Is this achievable? ...

Ways to align the icon and text to the left side of the screen?

I am looking to utilize Bootstrap's list group feature to create a navigation bar similar to the image below: https://i.sstatic.net/bndVl.png I am curious about how I can shift them to the left. Here is what I have attempted so far. .list-group-i ...

How to ensure a div within an anchor tag occupies the full width in HTML and CSS?

In my code, I am working on creating multiple small boxes with images and centered text inside. The goal is to have these boxes clickable, where clicking the image will take you to a specific link. On desktop, I want a hover effect that darkens the image b ...

Jquery draggable droppable does not support displaying multiple divs simultaneously

I tried to implement the jquery ui draggable and droppable features to display 3 divs within a designated area. Below is the code snippet: --CSS: #content-1 { width: 200px; height: 100px; border: 1px solid red; display: none; } #content-2 { width: ...

Modifying Background Images Dynamically with jQuery as You Scroll

Struggling to make my background image change while scrolling has been a challenge for me. I've tried different solutions suggested for similar questions, but so far no success - it only displays the initial background image. The setup involves havin ...

Scale first, then drag and drop to fix a faulty registration

I'm currently working on a project that involves dragging and dropping the correct items onto a technical drawing, such as a motherboard. The user is presented with pictures of components like CPUs or DDR memory and must drag these items to their corr ...

Hover over this area to reveal the hidden text as it slides into view

My goal is to hover over truncated text and reveal the full length of the dynamic text. However, I am struggling with removing extra space at the end of shorter text when hovered and displaying all the text for longer ones. I have a solution that almost w ...

Elevation on Tab button from the upper side

On my website, I have a large form where pressing the tab key switches between input fields. The inputs will also jump to the top if we reach the bottom of the form. The issue is that I have a fixed header at the top, covering the first 60px. Is there a w ...

Loop through an array of div IDs and update their CSS styles individually

How can I iterate through an array of Div IDs and change their CSS (background color) one after the other instead of all at once? I have tried looping through the array, but the CSS is applied simultaneously to all the divs. Any tips on how to delay the ...

Troubleshooting Bootstrap's Margin Problem

Currently, I am delving into the basics of bootstrap and encountering some challenges with using margin-auto. Specifically, I am working on positioning a navbar by using ml-auto to separate it from the brand, pushing the navbar to the right side of the p ...

Ensure that the div stays in the same position regardless of the screen resolution

On my webpage, I have a page header with a select menu that needs to be properly positioned on top of the background image. How can I ensure it stays in place when the screen resolution changes? Here is how it looks on a larger resolution: <div c ...

Embeddable video player failing to adjust size properly within parent div

I've been tackling the challenge of making iframes responsive within a div element, but I've hit a roadblock. While there are plenty of solutions available online, none seem to work seamlessly when dealing with YouTube video embeds. Currently, m ...