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

When a child element within a flex container has a relative position, the flex direction column will be overridden and

I'm having trouble with the code snippet below. For the .container, I have set display:flex; flex-direction: column; in order to position my previous and next arrows before and after the container items. However, the flex direction does not change ...

Bootstrap along with ROR 3.2.21 has a malfunctioning navbar

I am facing an issue with the Home section in the navbar. It used to work perfectly, but suddenly it stopped displaying as intended. I have checked and confirmed that both boostrap.min.js and boostrap.min.css are loaded properly. I have included boo ...

Aligning SVG shapes within each other

I recently encountered a scenario where I needed to position SVG shapes in the center of each other with varying scales. For instance, placing a rectangle or triangle within the center of a circle. While I found some solutions that worked for shapes like ...

Placing an element in a fixed position behind a non-fixed element

I am facing a challenge with an element that has two children, one of them is absolutely positioned. My goal is to position this absolutely placed element behind its sibling. Unfortunately, the z-index property doesn't seem to be working as expected. ...

Troubleshooting a mapping problem with CSS elements

While building my website, I have successfully mapped the elements by ID for all alphabet letters except A. When clicking on the letter A, it does not go to the respective elements. Can anyone please help me find a solution? Visit this link for reference ...

Unable to locate a resolution for the error message "Warning: Task "uglify" not found"

Below is the content of my Gruntfile.js: module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ uglify: { start: { files: { 'js/script.min.js': ['js/script.js&a ...

Irregular word spacing observed in HTML code

The alignment of text on my website is causing some spacing issues that I can't quite seem to resolve: It's an asp.net page, and I've attempted a couple of potential solutions: CSS .optionClosed { font-size: large; ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

Error with Bootstrap Layout caused by the StringBuilder

After diving into Bootstrap, I encountered an issue with the layout generated by a VB.NET page using StringBuilder. The result was a disorganized mess: Upon further inspection, it became evident that the problem extended to other sections of the page as w ...

Menu/navigation bar designed with floating lines and an array of color options

I'm currently working on implementing this specific menu into my Wordpress site. My main concern is figuring out how to customize the hover effect for each navigation item. Currently, the float line changes to red (background-color:#800; height:2px;) ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

Troubleshooting regex validation issues in a JSFiddle form

Link to JSFiddle I encountered an issue with JSFiddle and I am having trouble figuring out the root cause. My aim is to validate an input using a regex pattern for a person's name. $("document").ready(function() { function validateForm() { var ...

Is there a way to conceal a div class on the Payment page in Shopify?

I have encountered an issue with the code on the Shopify checkout (Payment) Page. Unfortunately, I am unable to directly edit this page within Shopify, but I have discovered that it is possible to add custom CSS or HTML code within the checkout settings of ...

Conceal the HTML input element until the JavaScript has finished loading

Currently, I am using a JQuery plugin to style a form input with type 'file'. The plugin adds a new span over the input element to create a mask effect and encloses everything in a div. However, there is an issue where the standard HTML input box ...

The menu bar becomes distorted when the page is zoomed out

Hey everyone, I could really use some assistance with my menus. Whenever I zoom out of the page, they become distorted. Here is the link to my website: https://dl.dropbox.com/u/22813136/Finding%20Nemo%20Inc/FNemo_front.htm# I tested the link on Internet E ...

Using a pseudo-element after to center CSS content

Although there are numerous posts discussing this topic, my situation is unique. In my case, I have a collection of colors represented by circles. When I click on a circle, I add content in the form of a check mark by including a class selector with an af ...

Scrolling horizontally to display dynamic columns based on a search query in AngularJS

I am facing a challenge with implementing search functionality in a table that has multiple dynamic columns with a horizontal scrollbar. The goal is for users to be able to search for a specific column name or data, and if a match is found, the scrollbar s ...

What could be preventing the background image from displaying properly?

I had the idea to create a game where players have to flip cards to reveal what's on the back, but I'm struggling to get the background image to display properly. As a newcomer to Vue, I'm not sure if I made a mistake somewhere. My intuition ...

I have tried using justify-content: center; and align-items: center; to center this div, but the container div is still not centered. How can I successfully center

I am having trouble centering the container in my HTML code HTML code:- <body> <div class="container"> <div class="image"> <img src="./images/image-qr-code.png" alt="qrcode"> & ...

Contrast between JQuery .display/.conceal and CSS view:invisible

I'm working on a way to toggle the visibility of a Div element using JQuery: $("#Progress").hide("fast"); But I want the #Progress div to be hidden by default. <div style="height:30px;margin-top:5px"> <div id="Progress" style="visibil ...