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

Once the <a> element is clicked, ensure that the function finishes executing before attempting to click/process it again

Utilizing jQuery.get for AJAX requests, I trigger a server request when the user clicks on the <a> element. The response is then used to update the content within the <div id='aaa'>. However, if the user clicks on the <a> rapid ...

What is the best way to iterate through only the selected checkboxes to calculate their

I am in need of calculating the selected checkboxes only within a table field (harga_obat*jumlah) Below is my foreach data: @foreach ($obat as $o) <tr> <td> <input id="check" type="checkbox" name="select[]" value="{{ $o->nam ...

Having trouble with the image not showing up using the code <img src="">

UPDATE :: I recently discovered that there is a permission error preventing me from accessing images in the images folder. It seems that I do not have the necessary "permission" to retrieve the image files ... * A few days ago, I posted a question regardi ...

Duplicate table row and insert new cell

I am currently attempting to duplicate a row from one table into a new table and then include an additional td at the end of the copied row containing a delete button. Thus far, I have successfully duplicated the row but am struggling to find a method for ...

Tips for aligning a menu that expands from the side to the center

I'm trying to center the menu on my webpage, but the issue is that it's stretching from the sides. Here's a sample image of the menu layout: I'm struggling to figure out how to fill the empty space on the left side of the menu. ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

How come my function does not properly update the visibility of the elements with each subsequent call?

I am currently implementing form validation and updating the display of a notification based on the status code received from an http request with the following code: function checkValidEndpoint() { var xmlHttp = null; var myurl = "/restyendpoint/ ...

Execute MySQL query when the content of an HTML text field changes

My goal is to check if the value entered in an input text box matches any rows in a database. I want the DB to be searched when text is typed into the input field. <input type='text' name='barcode'> I would like it to search the ...

Troublesome tab key function in FireFox causing navigation issues

I'm facing an issue with the tab key focus on links in FireFox. Strangely, it's working fine in Chrome but in FireFox, it keeps looping within one element. For better understanding, I have created a demo showcasing this behavior specifically in ...

The value of the comment box with the ID $(CommentBoxId) is not being captured

When a user enters data in the comment box and clicks the corresponding submit button, I am successfully passing id, CompanyId, WorkId, and CommentBoxId to the code behind to update the record. However, I am encountering an issue as I also want to pass the ...

Managing several instances of NgbPagination on a single webpage

I am facing a challenge with having multiple NgbPagination components on a single page. For more information, please visit: Initially, I attempted to use ids but encountered an issue where changing one value in the first pagination affected both tables. ...

What is the best way to align a GIF and two rows of text within a container div?

Check out my JSFiddle below: In this fiddle, there is an image sized 32 by 32 on the left side and two lines of text on the right. I need help aligning the center of the gif and the text with the middle of the enclosing frame. I've tried adjusting t ...

CSS: Caption text below image remains on same line

I am struggling with positioning a div that contains an image and a caption. My goal is to make the caption break into a new line when it reaches 95% of the width of the image. Despite my efforts, I can't seem to achieve this. The text always pushes ...

Use a boolean value to determine the styling of multiple items simultaneously

I'm currently attempting to modify the appearance of the bars in each area (a total of 12), so that a value of 1 equates to true (displayed as green) and a value of 0 equates to false (displayed as red). This will dynamically change the color of each ...

Align images to the left in Typora for a cleaner look

Typora typically aligns all images in the center by default. https://i.stack.imgur.com/TrqIM.png In my search through the github.css, I was unable to locate any instances of img. $ grep img "/Users/me/Library/Application Support/abnerworks.Typora/themes ...

Apply pointer style to the CSS only when a division contains text

If there is plain text inside a div with class="x95qze", how can we add cursor:pointer only to the second div that contains the text Cursor pointer required here. The div with class="x95qze" will not change. The content of the div may ...

Obtain ID and Class details from an HTML webpage using VBA

A few months back, I developed a program in Excel VBA to extract specific information about the prices of my game collection from an HTML page. Initially, it worked perfectly fine but suddenly stopped functioning about a month ago. I'm struggling to f ...

What is the process for displaying or hiding a large image when clicking on thumbnail images?

How can I toggle the display of a large image by clicking on thumbnails? This is what I am looking for: Check out this JSFiddle version http://jsfiddle.net/jitendravyas/Qhdaz/ If not possible with just CSS, then a jQuery solution is acceptable. Is it o ...

Curved edges, Layering, Content overflow restriction

My design consists of two circular divs with the border-radius property set to its max value. The first circle contains a header div with a unique background-color and overflow:hidden to create the illusion that the top portion of the circle has a differen ...

Loading Bootstrap Modal with click event triggering

I am currently working on a project where I need to load ajax content into a bootstrap modal when a link is clicked. I have been able to successfully load the content without any issues, but I am facing some difficulties triggering the modal window to open ...