Skip to content
Fix Code Error

How to vertically align an image inside a div

March 13, 2021 by Code Error
Posted By: Anonymous

How can you align an image inside of a containing div?

Example

In my example, I need to vertically center the <img> in the <div> with class ="frame":

<div class="frame" style="height: 25px;">
    <img src="http://jsfiddle.net/img/logo.png" />
</div>

.frame‘s height is fixed and the image’s height is unknown. I can add new elements in .frame if that’s the only solution. I’m trying to do this on Internet  Explorer 7 and later, WebKit, Gecko.

See the jsfiddle here.

.frame {
    height: 25px;      /* Equals maximum image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;

    text-align: center;
    margin: 1em 0;
}
img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=250 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=25 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=23 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=21 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=19 />
</div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=17 />
</div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=15 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=13 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=11 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=9 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=7 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=5 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=3 />
 </div>

Solution

The only (and the best cross-browser) way as I know is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.

So there is a solution: http://jsfiddle.net/kizu/4RPFa/4570/

.frame {
    height: 25px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    white-space: nowrap; /* This is required unless you put the helper span closely near the img */

    text-align: center;
    margin: 1em 0;
}

.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=17px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=15px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=13px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=11px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=9px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=7px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=5px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=3px />
</div>

Or, if you don’t want to have an extra element in modern browsers and don’t mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won’t be any performance issues:

The solution with :before and expression() for Internet Explorer: http://jsfiddle.net/kizu/4RPFa/4571/

.frame {
    height: 25px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    white-space: nowrap;

    text-align: center;
    margin: 1em 0;
}

.frame:before,
.frame_before {
    content: "";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}

/* Move this to conditional comments */
.frame {
    list-style:none;
    behavior: expression(
        function(t){
            t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');
            t.runtimeStyle.behavior = 'none';
        }(this)
    );
}
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>

How it works:

  1. When you have two inline-block elements near each other, you can align each to other’s side, so with vertical-align: middle you’ll get something like this:

    Two aligned blocks

  2. When you have a block with fixed height (in px, em or another absolute unit), you can set the height of inner blocks in %.

  3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it (<img/> in your case) vertically near it.
Answered By: Anonymous

Related Articles

  • Active tab issue on page load HTML
  • Pandas pivot_table: filter on aggregate function
  • Navbar not filling width of page when reduced to mobile view
  • insert tables in dataframe with years from 2000 to…
  • Having trouble with my nav bar/header, It used to…
  • Is it possible to apply CSS to half of a character?
  • How do I keep only the first map and when the game…
  • Azure Sql : Unable to Replace HTML String
  • After a little scroll, the sticky navbar just is not…
  • Add calculated column to df2 for every row entry in…
  • Centering in CSS Grid
  • SQL find sum of entries by date including previous date
  • I need to sum values with specific condition
  • Cannot make table responsive
  • How do I do a drag and drop using jQuery to move…
  • Fix top buttons on scroll of list below
  • Obtain most recent value for based on index in a…
  • How do I style a dropdown with only CSS?
  • CSS Input with width: 100% goes outside parent's bound
  • Jquery fadeToggle Trouble
  • Does bootstrap have builtin padding and margin classes?
  • How to use html template with vue.js
  • Adobe XD to responsive html
  • Increasing size of semi circle using css
  • Oracle sql query to group two sets of dates if sequencials
  • How do you get string interpolation working on a…
  • VueJS masonry layout
  • Nesting query results in BigQuery
  • How do i update a javascript variable as its value changes?
  • My DIV elements go diagonal instead of horizontal
  • Moving average in MYSQL without dates but grouped by…
  • How to show title in hover - css / jquery
  • JavaScript Loading Screen while page loads
  • Python Monthly Change Calculation (Pandas)
  • How to prevent scrolling the whole page?
  • In CSS Flexbox, why are there no "justify-items" and…
  • Python - Modifying rows of a data frame where the…
  • Is it possible to move my text side by side with my icon
  • How to use 2 columns as "key" to get MAX value of…
  • center 3 items on 2 lines
  • Reset/remove CSS styles for element only
  • Best way to extract messy HTML tables using BeautifulSoup
  • Pandas / Python - Compare numerically each row with…
  • Creating road sign style outline for a tag cloud
  • How to apply rolling t.test with pandas?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Why are CSS keyframe animations broken in Vue…
  • Why my "title" bloc doesn't go to bottom?
  • Jetty: HTTP ERROR: 503/ Service Unavailable
  • What does do?
  • how to access parent component scope from a child…
  • CSS selector for first element with class
  • CSS animate a conical gradient as border image
  • Content showing over the top of tooltip
  • How to stretch the div to all the height of the page?
  • Chrome / Safari not filling 100% height of flex parent
  • moving text and image in nav
  • Vertical Align Center in Bootstrap 4
  • CSS Variable trough Polymer (dynamically loaded) elements
  • How to convert Rows into Columns in Informix 12.10
  • How to properly do JSON API GET requests and assign…
  • Form field border-radius is not working only on the…
  • Animating Elements in One by One
  • How to center an element horizontally and vertically
  • How can I close an element when the div content or a…
  • Running Internet Explorer 6, Internet Explorer 7,…
  • Vue.js custom select component with v-model
  • html tables & inline styles
  • vue js cant understand keep alive
  • Triggering text area by clicking related select/checkbox
  • Can't install via pip because of egg_info error
  • Do not close the mode in the mouse up event
  • Onclick event not happening when slick slider is…
  • How to horizontally align ul to center of div?
  • Adding multiple dropdown menu's next to each other…
  • How to vertically center a container in Bootstrap?
  • How to create a game over screen for a basic HTML/JS game?
  • Columns side by side with css grid
  • Java web start - Unable to load resource
  • force css grid container to fill full screen of device
  • Print the significance of the relationship and…
  • Bootstrap 4.6 + CSS, how to bottom align a row
  • Why does writeObject throw…
  • How to align flexbox columns left and right?
  • Why is it that "No HTTP resource was found that…
  • Print tables with 3 regression output models from rdrobust
  • Why doesn't the height of a container element…
  • Content within div won't fill available space…
  • functions deleting the paint canvas
  • How get consecutives weeks in a group in df python?
  • Error 'Map', but got one of type 'Null' flutter web…
  • Positioned element is off when on Safari`
  • Hidden property of a button in HTML
  • How to properly use slot inside of vue js web…
  • How to format html table with inline styles to look…
  • center images with each other in logo carousel
  • Image on footer in Bootstrap
  • CSS DIV width based on text length with position…
  • Javascript validate all checkboxes are selected
  • Why doesnt my table sort my div variable in numerical order?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to round a number to n decimal places in Java

Next Post:

JQuery – $ is not defined

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error