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

Unexpected appearance of blank space to the right of my parallax design

Ever since a forced reboot, my parallax scrolling page has been experiencing issues. A strange whitespace seems to be throwing off the sections, only appearing every other section - one is fine, the next is offset, and so on. I've carefully gone thro ...

What causes the entire set of dynamically created cards to collapse when using the toggle collapse button in ngb-bootstrap's Collapse control?

I am currently implementing the ngb-bootstrap collapse feature in my Angular 9 application. Incorporating the ngb-bootstrap collapse functionality within a Bootstrap card, I have multiple cards being generated. Each card is equipped with a collapse button ...

Utilizing a combination of CSS and JavaScript, the traffic light can be altered to change based on

**I stumbled upon this online code snippet where a timer is controlled in CSS. I'm trying to figure out how to control it with JavaScript, but all my attempts have failed so far. Is there anyone who can help me solve this issue? What I'm attempti ...

Having trouble getting the `nth-of-type` and `nth-child` selectors in CSS to function

I am attempting to apply a green color for the first nth child flag element <div id="axis"> <div class="super"></div> <div class="flag">flag 1</div><!-- I want this text to be green--> <div class="supe ...

Incorporate text inside the border of a Material UI chip

https://i.stack.imgur.com/VATrD.png I'm looking to replicate this design using a pre-built Chip component from MaterialUI While the solution might involve Some Text using html and css, it still may not achieve an identical result. I've come acr ...

determining the perfect size of a container by analyzing its content

Displayed here is a snapshot of content included in form validation for a website project that's currently in development: The content is currently situated within a div element with its width set to 20%. Initially, without this rule, the div spanned ...

What is the best way to manipulate the size and orientation of an image upon hovering over

I'm struggling to figure out how to simultaneously rotate and scale a .png file when the user hovers over it. Currently, it only scales when I hover on the picture. I understand that the scale property overwrites the first transform but I can't s ...

Animation issue in Material UI autocomplete label feature

Hello, I am currently delving into the world of React and Material UI. I have been working on implementing the Material UI auto complete feature with chip functionality. You can see my progress here: https://codesandbox.io/s/runh6. Everything seems to be w ...

Encircle a circle within the Progress Tracker

Is there a way to create a ring around the circle in this progress tracker, similar to the image shown here? The progress tracker is based on You can view an example here. The CSS approach used was: .progress-step.is-active .progress-marker { backgrou ...

What is the best method for incorporating a unique style to a v-dialog component in Vuetify following the most recent update?

I'm currently working on a project using vuetify, and I am facing an issue while trying to add a custom class to a v-dialog component. I have tried searching for information on how to do this, but it seems that the prop "content-class" has been deprec ...

Retrieve the value of a PHP array within a for loop and transfer it to JQuery

*edited format I came across a PHP code for a calendar on the internet and I am currently working on implementing an onclick event that captures the date selected by a user as a variable (which will be used later in a database query). At this point, my g ...

Ways to maximize the amount of content contained within a box

My current struggle involves meeting the requirements of my customers. I have a small box (230px x 200px) with an image that will display a list on hover. However, the customer now wants more items in the list than can fit in the box. Scrolling within the ...

What is the method for placing a badge above a Font Awesome icon?

Is it possible to add a badge with numbers like 5, 10, or 100 on top of the Font Awesome symbol (fa-envelope)? I am looking for something like this: However, I am struggling to figure out how to place the badge on top of the symbol. You can see my attempt ...

The process of creating a React build varies greatly from the initial development phase

Thank you for offering to help me! After building my React web app, it looks very different from development mode. I use serve -s build to monitor the app build. However, even on my online DigitalOcean server, it doesn't appear the same as in develop ...

Enhancing the design of a button with whitespace using CSS

Recently, I had a well-designed landing page created using LeadPages. However, due to financial constraints, I am unable to continue paying for their services at the moment. The current landing page has proven to be effective in converting leads. https:// ...

Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed. ...

Issue with Firefox not entering FullScreen when using the userChrome.css file

1) Below is a screenshot of my customized Firefox interface. After tweaking my userchrome.css file to remove tabs, I noticed a large empty space at the bottom of the browser window that I cannot seem to get rid of. Despite trying various solutions, I have ...

Elements resize based on their parent's and siblings' widths

I have organized the parent div and its three children divs. Presently, the third child is concealed. I've designated the width of the first child as 20% and desire for the second child to automatically take up the remaining width without explicit set ...

Exploring the power of directives in AngularJS for dynamically manipulating the

Using angular directives, I am attempting to dynamically replace a portion of HTML within a portlet on a webpage. The portlet contains two embedded sections. The top section includes a heading obtained from a separate backend service. <div class="head ...

Apply the `text-overflow: ellipsis` property to truncate the text of two items within a flex column, which is contained within

I am attempting to accomplish the following: Successfully implementing ellipsis for a single item is achieved with: white-space: nowrap; overflow: hidden; text-overflow: ellipsis; However, my challenge lies in truncating two items. One should appear be ...