Alignment of images at the center within a container div while maintaining a height of 100%

Apologies if this question has already been addressed - I have tried numerous methods to center images horizontally without success. This particular image just does not want to align in the center!

For reference, here is the JSFiddle link

HTML: (Please note that the images used are taken from Google as examples)

When loading, each image receives either "height:100%;" or "width:100%;" based on whether the height to width ratio falls within or outside of the 4:3 ratio in landscape orientation.

This setup ensures that the image completely fills the containing div regardless of its size and shape.

<div class="imgOuter">
    <div class="imgInner">
        <img src="http://www.woroni.com.au/wp-content/uploads/2013/12/Cars-Lamborghini-Free-Wallpaper.jpg" style="height: 100%;">
    </div>
</div>
<div class="imgOuter">
    <div class="imgInner">
        <img src="http://cdn.acidcow.com/pics/20100118/celebrity_portraits_by_tom_munro_03.jpg" style="width: 100%;">
    </div>
</div>

CSS:

The main outer div is designed to maintain a fixed aspect ratio of 4:3 The inner div adds an internal border to the outer div which must retain its specific dimensions.

div.imgOuter{
    float: left;
    position: relative;
    width: 33.3333%;
    padding-bottom: 25%;
    overflow:hidden;
    clear:none;
}
div.imgInner{
    position:absolute;
    top:0;bottom:0;left:0;right:0;
    overflow:hidden;
    text-align:center;
    border:2px solid #444;
    cursor:pointer;
}
div.imgInner>img{
    display:block;
    position:absolute;
    top:0;bottom:0;left:0;right:0;
    margin:auto;
}

.imgInner: I have experimented with text-align:center; also tested sizing with height and width @ 100%...

In the attached fiddle, you will notice that the second image, in portrait orientation, aligns perfectly centered vertically as expected.

Moreover, when using a landscape image and setting the width to 100% instead of the height, it centers vertically flawlessly, resulting in white space above and below if its ratio is wider than 4:3.

Only when the height is set to 100% does the image default to left alignment, seemingly disregarding the left and right positioning.

My suspicion lies in the fact that the div.imgOuter lacks a defined height, only having a padding value. If that indeed is the issue, I am faced with the challenge of resolving both scaling aspect ratios and center alignment :(

Do you have any suggestions?

Answer №1

It seems that achieving both horizontal and vertical centering using only CSS is quite challenging, especially when dealing with negative margins in relation to the parent container's size. However, a JavaScript solution can do the trick.

If you're interested, here's a helpful JSFiddle example: http://jsfiddle.net/HkuMW/7/

To position an element in the exact middle based on its top-left corner, apply percentages to the left and top properties like so:

div.imgInner>img {
    display:block;
    position:absolute;
    top:50%;
    left:50%;
}

Next, use jQuery to calculate and adjust the image's position by determining the dimensions and applying half of them as margins:

$('.imgInner > img').each(function (i) {
    var imgWidth = ((0 - parseInt($(this).css('width'))) / 2);
    var imgHeight = ((0 - parseInt($(this).css('height'))) / 2);

    $(this).css('margin-top', imgHeight);
    $(this).css('margin-left', imgWidth);
});

Answer №2

Take a look to see if this addresses your inquiry.

http://jsfiddle.net/HkuMW/17/

If necessary, you can swap the resizing method from background-size:100% auto; to background-size:auto 100%;.

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

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

What could be causing the issue with my Date and Time input not functioning correctly?

I developed a React frontend application styled with Material UI design. The issue I am facing is that after adding the Date and Time component styling to the form, it is unable to process the "name" value for posting. Specifically, the error message "Ty ...

Troubleshooting the issue of browser prefix injections not functioning properly in Vue when using the

I've spent an entire afternoon on this issue and I'm completely stuck. After realizing that IE11 doesn't support grid-template, I learned that I need to use -ms-grid-columns and -ms-grid-rows instead. I am attempting to generate CSS and inje ...

What steps can be taken to restrict a user's access to the main page unless they are logged in?

I have created sign up and login pages using JavaScript, HTML, and PHP with a database. After a user successfully logs in on the login page, the following code is executed: sessionStorage.setItem('logged','loggedIn'); The user is then ...

Utilize React JS to incorporate multiple instances of the Bootstrap carousel within a webpage using Reactstrap

I am having difficulty using the bootstrap carousel multiple times on a single page. I have attempted to copy it as a new item numerous times, but I keep encountering errors. <CarouselItem onExiting={() => setAnimating(true)} onExited={() => ...

Minimize the expansive width of Shiny Dashboard's sidebar for

I'm facing a challenge in hiding a shinydashboard sidebar with a wider width. Upon increasing the width, however, the sidebar isn't completely disappearing from the screen. Here's an example that illustrates the issue I'm trying to add ...

Is retrieving data from the database causing unexpected additional space to appear in the textarea?

I am facing an issue with a basic php file that fetches information from a MySQL database and displays it inside a textarea. However, when I access the file through browsers, there seems to be extra space at the start and end of the text within the textare ...

Is it possible to manipulate the content inside a div tag using JavaScript in HTML?

What is the most efficient way to dynamically adjust a data offset value within an HTML tag using JavaScript? For example: <div class="box" data-offset="2s"></div> I am looking to update the value within the data-offset attribute based on s ...

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

How can I use cookies to make an HTML div disappear when a button is clicked?

I've been attempting to conceal this message in Vue.js, but so far I haven't had any luck. Currently, I am utilizing the js-cookie library. My objective is as follows: HTML <div v-show="closeBox()"> < ...

Stop the replication of HTML/CSS styles during the extraction of content from a div

Is there a way to prevent the copying of CSS properties, such as font styles and sizes, when content is copied from a div? I want only the plain text to be copied to the clipboard, without any formatting applied. ...

An adaptive image-based menu design that adjusts based on screen size

Although I can get it to function properly, the trouble arises when I attempt to resize it for responsiveness, resulting in a strange scaling issue. Essentially, I want the images to remain at their natural size and align next to each other seamlessly with ...

Connecting CSS styles and images to my EJS templates on a distant Express server using Node.js (Ubuntu 18.04)

I have been hunting for a solution here extensively, but every attempt has failed. So, here's the issue I'm facing: I have created a basic Express server locally to display a static page until I finish full integration. The structure of my site ...

Looking for assistance in creating a stunning portfolio showcase?

As I work on building my portfolio webpage, I've realized that with my limited knowledge of HTML/CSS, creating a great gallery might be challenging. In search of an efficient solution, I ventured across the web but couldn't find anything that ful ...

Issue with Left Alignment of Tabs in Material-UI

As of now, material-ui's latest version does not provide support for aligning tabs to the left in the component. However, I came across a workaround on this GitHub page I have implemented the same workaround, and you can view it here: Unfortunately, ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

The outcome of the Python web crawling did not meet our expectations

After using Selenium to scrape web data, I encountered an issue where it only displayed 96 out of 346 products instead of the expected 346. Does anyone have suggestions on how to fix this problem? The crawling code is placed right after the loop for clicki ...

The Bootstrap accordion-toggle incorrectly displays the content symbol (+/-) upon initial page load

Hey there, I've implemented the accordion-toggle code below on my visualforce page. Everything is working smoothly with the collapsible toggle, except for one issue. When loading or refreshing the page for the first time, the collapsed panel shows the ...

How can I remove the unsightly scrollbar caused by overflow: auto?

I've encountered a problem while working on my website. The inner div #content wasn't expanding to the full size of the page, causing the text to overflow messily over the background image and making it difficult to read. I initially used overflo ...