Center the cropped image within a div container

Is there a way to set a maximum height for a div containing an image and hide the parts of the image that exceed this height, while keeping it centered vertically inside the div? For example, if the browser width is 1200px and the image aspect ratio is 4:3, the image should display at (1200x900)px. However, if we want to crop the height to 300px and center it vertically, the image should be positioned at -300px inside the div.

This may require JavaScript, but I'm curious if there's a CSS solution as well. Thanks in advance!

Answer №1

Here is my perspective on this: http://codepen.io/vsync/pen/DpmnK

HTML Code Snippet

<div class='box'>
  <img src="http://www.biztalk360.com/Events/BizTalk-Innovation-day-2014-Norway/images/banner.jpg">
</div>

SCSS Styling

.box{
  // defining the image container dimensions 
  width:100%;
  height:100px;

  // The magic happens here
  > img{
    position:absolute;
    z-index:-1;
    top:50%;
    left:50%;
    width:100%;
    transform:translate(-50%, -50%); 
    &.max{ width:auto; height:100%; }
  }
}

Javascript Function for Responsiveness

var photo     = document.images[0],
    container = document.querySelector('.box');

$(window).on('resize.coverPhoto', function(){
  requestAnimationFrame(checkRatio);
});

function checkRatio(){
  var state = photo.clientHeight <= container.clientHeight && 
              photo.clientWidth >= container.clientWidth;

  photo.classList[state ? 'add' : 'remove']('max');
}

Answer №2

If you're interested, check out this question: Resizing an oversized image using overflow:hidden and maintaining the aspect ratio

http://codepen.io/gcyrillus/pen/Grbxg

.grid_3 { width:260px; margin:0 20px; float:left; text-align:center;
  overflow:hidden; background:rgba(255,255,255,0.02);}

.grid_3 a {
  display:block;  
  height:171px; border:solid 2px #FFFFFF;
  line-height:168px;
  overflow:hidden;
  margin-bottom:10px;
}
.max-img-border { width:100%; margin:-100% 0; vertical-align:middle;
}

Here's another example pen that explores vertical-align:middle with an image having virtually no height in the flow: http://codepen.io/gc-nomade/pen/DxCgv

Keep in mind that setting an image in the background center is simple if it doesn't need to convey any specific meaning in your content.

Answer №3

Are you looking to have the div act as a window for your image display? It reminds me of image sprites, which is when multiple icons are combined into one large picture and then displayed individually:

http://www.w3schools.com/css/css_image_sprites.asp

If you share a JSFiddle link with me, I can offer more specific help.

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

Arrange DIV elements sequentially with HTML, JQuery, and CSS

Live Demo: Live Demo HTML: <div class="target"> <img src="bg-clock.png" alt="jQuery" /> </div> <div class="target2"> <img src="bg-clock.png" alt="jQuery" /> </div> CSS: .target, .target2 { ...

Embed the YouTube video using the URL in the video tag

I tried using the <video> tag, but I'm having trouble getting it to play videos from YouTube. Even though I found this http://jsfiddle.net/wCrNw/, it doesn't seem to work as expected. I also consulted Show Youtube video source into HTML5 ...

Which is the better approach for performance: querying on parent selectors or appending selectors to all children?

I currently have 2 mirror sections within my DOM, one for delivery and another for pickup. Both of these sections contain identical content structures. Here's an example: <div class="main-section"> <div class="description-content"> ...

Hovering over the designated area will reveal the appearance of

I've encountered an issue with a list group in a card. Specifically, when hovering over the topmost item in the list group, a border appears underneath it (which should only appear when hovering). However, when I try to override this behavior using :h ...

Guide to aligning a URL in an HTML file

Greetings all, I'm new to HTML and struggling with how to center a URL on my webpage. For example: <a href="http://www.google.com"> Click Here to Open Google </a> I attempted using the tag and the STYLE attribute but without success. ...

Resizing the width to fit truncated content

When displaying text within a span element inside a fixed-width structure, I want to use ellipsis if the text overflows. To show the full text, I have initialized a Bootstrap tooltip in these elements. However, the tooltip is visually misplaced due to the ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

What is the best way to place a horizontal line behind buttons in a design?

Hello, I was experimenting with creating a background line behind the buttons on my webpage. Previously, I used an image for this purpose but now I want to achieve the same effect using a line. <div class="feedback-option"> <div class="radios2" ...

Learn how to retrieve data using the $.ajax() function in jQuery and effectively showcase it on your HTML page

Can someone assist me with extracting data from https://jsonplaceholder.typicode.com/? Below is the AJAX call I'm using: $.ajax({ url: root + '/posts/', data: { userId: 1 }, type: "GET", dataType: "json", success: function(data) { ...

Duplication of elements in a Meteor and React environment

When it comes to creating a basic Meteor app with React, this is the structure I have put in place: <head> <title>test</title> </head> <body> <div id="render-target"></div> </body> Here is the start ...

@page Css not displaying properly on the Mozilla Firefox browser

In order to fulfill my requirement, I need to ensure that there is a consistent 10cm margin on all pages when printing. Printing on my web page involves utilizing the window.print() function. However, due to the dynamic nature of the content, the number o ...

Optimal techniques for leveraging CSS within Mui and Reactjs

Just starting out with mui, I'm currently working on styling CSS for mui components like so <Typography variant="h5" sx={{ fontWeight: "bold", color: "#1a759f", display: "flex", ...

Tips for converting numerical values to visual elements in a JQUERY slider for images

I am looking to incorporate a similar image slider on my website, like the one showcased here: . However, I want the bottom content numbers to be replaced with smaller versions of the images in the slider instead. Does anyone have any suggestions on how I ...

Spartacus 3.3 - Unleashing the Full Potential of the Default Sparta Storefront Theme

Looking for advice on how to customize the default Spartacus Storefront theme (Sparta) by only overriding specific CSS vars. Any suggestions? I tried following the instructions provided at: https://github.com/SAP/spartacus/blob/develop/projects/storefront ...

What is the purpose of using the "::before" CSS modifier to display the fontawesome chevron in the specified Bootstrap accordion code?

I stumbled upon a great example of adding arrows to the Bootstrap accordion on CodePen. Check it out: https://codepen.io/tmg/pen/PQVBGB HTML: <div class="container"> <div id="accordion"> <div class="card"& ...

Anchors that need to be clicked multiple times before activating

'I recently encountered a strange bug. My CSS3 anchors/buttons, which I have been simplifying by removing properties, sometimes require multiple clicks to function. This is completely new to me and quite perplexing. The issue seems to occur randomly, ...

Saving downloaded web pages as an HTML document

I'm looking to extract the HTML content of a webpage. Within this HTML, there are two specific elements with XPaths that I need to retrieve. Unfortunately, my knowledge on this subject is quite limited. While searching for solutions, most examples in ...

Creating glitchy dotted lines in an HTML Canvas with the help of translate and scale techniques

I'm working on creating a canvas where users can draw symmetrical lines with their mouse. However, when I use the transform and scale attributes in the draw function to achieve this effect, it creates small gaps in the line and makes it look less smoo ...

Adding a border to dynamically generated content while excluding the outer borders using CSS - an easy guide

My current project involves establishing a grid system that dynamically populates content, resulting in an uncertain number of elements being created. At the moment, each element is placed within a flexbox container with 3 elements per row. If there are mo ...

Setting an Element's attribute is only visible in the console

Just dipping my toes into the world of Web Development. While playing around with some JavaScript within HTML, I decided to try updating the content of an element. Upon running the code below, "Updated Content" appears in the console as intended. However, ...