Create a focal point by placing an image in the center of a frame

How can an image be placed and styled within a div of arbitrary aspect ratio to ensure it is inscribed and centered, while maintaining its position when the frame is scaled?

  1. Ensure the image is both inscribed and centered
  2. Set dimensions and position using relative values so it remains inscribed and centered when uniformly scaled, requiring minimal javascript
  3. Minimize extra markup

Desired result:

See a fiddle template, with the following:

Markup

Should pillarbox
<div class="frame">
    <img src="http://www.placekitten.com/200/300" />
</div>

Should letterbox
<div class="frame">
    <img src="http://www.placekitten.com/300/200" />
</div>

CSS

.frame {
    width: 200px;
    height: 200px;
    border: 2px solid black;
    margin: 10px 0px 100px 0;
}

Answer №1

If you're looking to achieve a specific layout, consider implementing something along these lines: check out the updated fiddle here

.frame {
    width: 200px;
    height: 200px;
    border: 2px solid black;
    margin: 10px 0px 100px 0;
    position: relative; /* added */
}

img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    margin: auto;
    top: 0; left: 0; bottom: 0; right: 0;
} 

Answer №2

Combining the Adrift's css technique has proven to be a successful approach.

.frame {
    width: 400px;
    height: 400px;
    border: 2px solid black;
    margin: 10px 0px 100px 0;
    position: relative; /* added */
}

img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    margin: auto;
    top: 0; left: 0; bottom: 0; right: 0;
} 

When coupled with javascript code:

var inscribe = function(img, frame) {
    var imgRatio = img.width / img.height;
    var frameRatio = frame.offsetWidth / frame.offsetHeight;

    if (imgRatio > frameRatio) { // image is wider than frame; letterbox
        img.style.width = '100%';
        img.style.height = 'auto';
    } else {                     // image is taller than frame; pillarbox
        img.style.width = 'auto';
        img.style.height = '100%';
    }
}

All requirements can now be met successfully.

Explore the solution here

Answer №3

You can also achieve this using background images instead of <img /> elements.

A helpful CSS property is background-size with the value of contain:

.image{
   background-size: contain;
}

To center the image, simply include:

background-position: center center;

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

Combining two arrays in React using TypeScript and showcasing them in a single list display

I am working on a React TypeScript project and have two comma-separated strings that I am converting into arrays. One array contains the file names, and the other contains the file link paths. My goal is to merge the two arrays so that the first item in th ...

Position the form / delete button in alignment with the rest of the buttons

I have a table with options at the end like View, Edit, and Delete. I need the Delete button to be inside a form so that I can POST the delete request. However, my button/form is not aligning on the same line as expected. I have tried using the form-inlin ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Is there a way to have dynamic content from angularJS show up in an iframe?

When working with tabular content generated using ng-repeat in AngularJS, it is important to find a way to display this content within an iframe. The goal is to allow users to drag and resize the content as needed. However, using the iframe src attribute ...

The post request fails to send certain variables

I'm experiencing an issue with a form that has rows structured like this: <div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeNam ...

change visibility:hidden to visible in a css class using JavaScript

I've put together a list of Game of Thrones characters who might meet their demise (no spoilers included). However, I'm struggling with removing a CSS class as part of my task. Simply deleting the CSS is not the solution I am looking for. I' ...

Arranging data into columns using HTML and CSS

I'm currently working on a CSS solution to organize various elements like buttons and text in a tabular column format. My main challenge lies in controlling the layout effectively, especially since CSS columns are not compatible with IE9 and earlier v ...

Having trouble displaying database model information in the template

My challenge is displaying information from the Django third model (class Jenkinsjobsinformation) in the template. I've been successful in showcasing data from the first and second models (Projectname and Jenkinsjobsname). See below for a snippet of m ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

Encountered an issue following deployment to Heroku (Application error)

Introduction I recently created a Login form for my project. The frontend is deployed on Netlify at this link, and the backend is hosted on Heroku which can be accessed here. To view the backend logs, click here Here is a snippet of my index.js file: co ...

A minimalist dropdown menu using only HTML and CSS with an onclick function

I have been working on creating an onclick dropdown menu for mobile devices that should disappear when viewed on wider screens, but I've encountered an issue where the links in the menus are not clickable even though the @media query is set up correct ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

The data from the Ajax request failed to display in the table

JavaScript Code</p> $(function (){ $.ajax({ type : 'GET', url : 'order/orders.json', dataType : 'JSON', success: function(data) { /*var trHTML = ''; $.each(orders, function (i, it ...

Looping through arrays using ng-repeat

{ "employees" : [ { "name" : "XXX", "id" : "1", "Salary" : [ { "Month" : "XXXX", "Amount" : "XXXX", }, { "Month" : "XXXX", "A ...

Angular JS - A guide to implementing ng-model binding at a later stage

In a large codebase, there is a straightforward scenario that I need help with: There is an Angular APP and Controller already set up and functioning correctly. However, a ng-model element needs to be dynamically created at a later stage (perhaps through ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

The v-for loop is looking for a numerical value, but it received something that is Not

The v-for directive is having trouble accessing the nStars prop in order to run a loop. I am attempting to display multiple stars by using the component <display-stars>. However, the component does not seem to be receiving the nStars prop for the loo ...

Selenium: Utilizing the get_attribute() function with a CSS query

I am attempting to retrieve the value of the title attribute. There are multiple links on the page and I need to specifically select the first link and extract its title attribute. Here is the selenium command that I have used: self.se.get_attribute("c ...

Display a unique button and apply a strike-through effect specifically for that individual list item

I've encountered an issue with my code that is causing problems specifically with nested LI elements under the targeted li element: $('#comment-section .comment-box a#un-do').hide(); $('#comment-section ul li[data-is-archived="true"]& ...