Aligning an image of variable size perfectly both in the center horizontally as well as vertically

After extensive research, I have come across numerous solutions to this issue, but none of them have proven effective in my specific scenario. Here is a JSFiddle link illustrating the problem at hand:

http://jsfiddle.net/kr394ye2/1/

.classA {
    background-color: yellow;
    width: 50px;
    height: 50px;
    float: left;
}
.classB {
    width: auto;
    height: auto;
    max-width: 50px;
    max-height: 50px;
}
<div class="classA">
    <img class="classB" src="https://www.google.com/logos/doodles/2015/ida-b-wells-153rd-birthday-4853060954226688-hp.jpg"></img>
</div>

I am attempting to center an image both horizontally and vertically within its containing div, with the image automatically adjusting to fit the size of the div. It is important that the image remains an inline element and not a background.

Various methods such as using auto margins, display properties, text-align, vertical-align, and even the center tag have all been attempted without success.

An ideal solution would effectively center the image both horizontally and vertically within the div.

Answer №1

To achieve this layout, you can utilize the inline block technique along with pseudo elements.

.boxA {
    background-color: cyan;
    width: 70px;
    height: 70px;
    float: left;
    text-align: center;
    font-size: 0;
}
.boxA:after {
    content: "";
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}
.boxB {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    display: inline-block;
    vertical-align: middle;
}
<div class="boxA">
    <img class="boxB" src="https://www.example.com/image.jpg">
</div>

Keep in mind that this solution is effective only when the image is the sole child element within the container and when the container's height is specified.

Also note that <img> is a self-closing tag, so use <img src=""> instead of incorrect syntax like <img></img>.

Answer №2

Implement the following CSS code:

.classB {
    margin: auto;
    max-width: 50px;
    max-height: 50px;
}

Answer №3

For both vertical and horizontal centering, this is the solution you're looking for.

Click here for an example

Generally speaking, using

    margin:0 auto;

works wonders.

Alternatively, if you only need horizontal centering, just apply

margin-left:auto;
margin-right:auto;

to your main wrapper.

Answer №4

Update your CSS as follows:

.classA {
    background-color: yellow;
    width: 50px;
    height: 50px;
    padding: 5px;
}

.classB {
    display: block; margin: auto;
    object-fit: cover;
    max-width: 100%;
    height: 100%;
}

The CSS property object-fit: cover is useful for maintaining image quality while fitting it to a container.

Check out the JSFiddle demo here

Learn more about object-fit at object-fit - MDN Docs

Answer №5

Have you experimented with using display: table-cell on the parent div instead of block or inline-block? This might help achieve the alignment you're seeking.

Answer №6

Here are the four essential lines of code you'll need for perfect alignment:

  • text-align: center; applied to the parent element handles horizontal positioning
  • position: relative;, top: 50%;, and transform: translateY(-50%); work together to center images vertically

I've included two blocks with different sizes but identical properties to demonstrate its versatility. Tested and confirmed compatibility with latest versions of Chrome, Safari, IE10, and Opera.

.classA {
    background-color: yellow;
    width: 300px;
    height: 50px;
    float: left;

    text-align: center;
}

.classB {
    width: auto;
    height: auto;
    max-width: 300px;
    max-height: 50px;

    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
            transform: translateY(-50%);
}

.classA2 {
    background-color: yellow;
    width: 100px;
    height: 70px;
    float: left;

    text-align: center;
}

.classB2 {
    width: auto;
    height: auto;
    max-width: 100px;
    max-height: 70px;

    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
            transform: translateY(-50%);
}

.separator {
    display: block;
    clear:both;
    padding:20px;
}
<div class="classA">
    <img class="classB" src="https://www.google.com/logos/doodles/2015/ida-b-wells-153rd-birthday-4853060954226688-hp.jpg"></img>
</div>
<div class="separator"></div>
<div class="classA2">
    <img class="classB2" src="https://www.google.com/logos/doodles/2015/ida-b-wells-153rd-birthday-4853060954226688-hp.jpg"></img>
</div>

Hopefully, this solution proves helpful to you :)

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

Utilize a dynamically generated href to execute a C# function

I am currently in the process of creating a dropdown menu using HTML ul & li tags. Everything is working smoothly so far, but I have encountered an issue. Whenever there is an anchor tag (as indicated by the in-line comment), I would like to call a f ...

HTML text field within the same line

Is there a way to create multiple text fields on the same line? I have tried this code: <div class="col-lg-2"> <div class="form-group"> <label>Working experience</label> <input type="text" class="form-contro ...

Tips for choosing a dropdown option that will appear first in Bootstrap

I am working on a feature where I want to select the content I click on, and it should be the first one to be selected. Similar to how the select option works. Here is the image related to this topic. I am unsure about how to achieve this in my demo: htt ...

"Enhanced visuals with parallax scrolling feature implemented on various sections for an engaging

With 4 sections, each featuring a background image and text in the middle, I encountered an issue when attempting to have them fixed while scrolling. The goal was for the section below the first one to overlap the one above it along with its text as we scr ...

I must break free! Angular's $sce is failing to manage links to audio files (Strict Contextual Escaping)

I have successfully implemented Angular and $sce in my project to handle HTML special characters and link video files in the database to a video player. However, I am facing issues connecting the HTML audio player to audio files stored in the same database ...

Tips for meeting a JavaScript door unlocking condition with an HTML button

In this tutorial, the https://www.w3schools.com/nodejs/nodejs_raspberrypi_webserver_websocket.asp link demonstrates an event handler that works based on an HTML checkbox. I am interested in achieving a similar functionality, but with a button instead, to t ...

Issues with Adsense on a PHP website

I am experiencing a challenge with my Adsense account, as it is working on one site but not on another one. The non-functioning site is written in PHP, and despite trying different variations of the code, I am unable to display the ads successfully. The ...

The CSS Grid extends vertically beyond its bounds, rather than activating the overflow-y property

Why does the grid blow out in the following snippet? The grid has a lime green border, each child has a dotted red border, and you can see the dotted red extends beyond the lime grid border. The .child2 should be made scrollable to prevent the grid from bl ...

The formatting for C++ lnk2019 and lnk2020 is correct

Seeking assistance with my code and the errors I'm encountering - any guidance would be highly valued. Currently facing an issue with getNextAcountNumber. I attempted to assign the account ID value, but encountered a problem as it is a private member ...

Setting up an image background in three.js: A beginner's guide

I tried setting up an image background for my scene with a globe in three.js, but unfortunately, the main object of my scene turned black (the same color as the background). I attempted using the following method: renderer = new THREE.WebGLRenderer({ anti ...

Having an issue with button onClick functionality not working in Javascript

Simple enough. I am struggling to get my button to generate the necessary input upon clicking. The fields should populate where the "household" class is located. I am limited to editing only Javascript and not HTML. Any suggestions? HTML: <ol ...

website: What is the best way to embed an input field within an image?

Is it possible to incorporate an image into my website design similarly to Google's simple approach? <img src... done... > Additionally, I would like to add an input box over the text area of the picture. How can I achieve this? ...

Formatting text over an image

The challenge I am facing involves having an image and text on it in two separate divs with a background color. The length of the text in one div is long while the text in the second div is short, but I want to ensure that the width of both divs are equal. ...

Tips on removing a stylesheet while transitioning to another page in Vue

I'm new to Vue.js and I'm experimenting with adding and removing stylesheets in components using the mounted and unmounted lifecycles. Initially, I successfully added a stylesheet using the following code: mounted() { this.style = document. ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

Is it possible to open a new tab by clicking on an anchor tag

I have a scenario with two tabs on a webpage, each with anchor tags that I can navigate to from the homepage using a header menu item anchor. The tabs are working fine with an active class and aria-expanded="true", but I'm facing an issue where the ap ...

Deselecting options using jQuery

Currently, I am facing a challenge with jQuery in deselecting a select option element. Let me explain my situation: I have 3 select options: [ Select 1 ] [ Select 2 ] [ Select 3 ] Situation: Initially, Select 1 is populated with data retrieved from ...

What is the best way to align div elements in HTML5?

I've spent countless hours trying to properly display and align multiple divs. Despite extensive research, I just can't seem to get it right. What I'm aiming for is to have the title of a section in the top left corner, an info box to the l ...

Assistance with Parallax Mouse Movement, Using JQuery, HTML, and CSS

As a newcomer to JQuery, I decided to experiment with creating a parallax background effect using the mousemove function. By utilizing event.pageX to generate a variable for adjusting the background position, I was able to achieve the desired result. Alth ...

Failure to Include jQuery in Header.php File

After adding the jQuery library to header.php, I encountered an issue where index.php was unable to access the library. Surprisingly, when the library was referenced directly from index.php, access to the jQuery library worked without any problems. Here i ...