I have a markup like this:
<div> <img /> </div>
The div is higher than img:
div { height: 100px; } img { height: dynamic-value-smaller-than-100px; }
I need the image to be in the middle of the div (have same amout of white space above and below it).
I tried this and it does not work:
div { vertical-align: middle; }
Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
You can just set text-align to center for an inline element, and margin: 0 auto would do it for a block-level element.
We need to create a parent element that contain both image and text. After declaring the parent element as flexbox using display: flex; we can align the items to the center using align-items: center;. Example: This example uses flexbox to vertically align text next to an image using CSS.
if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background
background-position: center center;
If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:
div{ display: table-cell; vertical-align: middle }
Read more about this technique here. Reported to not work on IE6/7 (works on IE8).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With