Brandion Langlois February 2016

How to vertically center and right-align an image?

I want an image to be on the right side of a <div> but centered vertically.

enter image description here

I would like it to be flexbox or as simple as possible.

#container1 {
  width: auto;
  height: auto;
}
#div1 {
  width: 400px;
  height: 200px;
  border: 1px solid black;
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: center;
}
#some_image {
  width: 50px;
  height: 25px;
}
<div id="container1">
  <div id="div1"><img id="some_image" src="some_image.gif"></div>

Answers


Marcos Pérez Gude February 2016

The best and simplest way (compatible with all browsers) it's to use transform: translate() function combined with position: absolute. It allows to center (horizontally and/or vertically) without pre-known the size of the box, for example:

#container1 {
  position: relative;
  width: 100%;
  background: blue;
  height: 100px;
  margin: 20px 0;
}

#div1 {
  position: absolute;
  right: 20px;
  top: 50%;
  -webkit-transform: translateY(-50%); /* safari ios*/
  -ms-transform: translateY(-50%); /* old IE */
  transform: translateY(-50%); /* standard */
  background:red;
  color:white;
}
#div2 {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%,-50%); /* safari ios*/
  -ms-transform: translate(-50%,-50%); /* old IE */
  transform: translate(-50%,-50%); /* standard */
  background:red;
  color:white;
}
<div id="container1">
    <div id="div1">Something you want</div>
</div>

<div id="container1">
    <div id="div2">Something you want</div>
</div>


Paulie_D February 2016

You were close

Flexbox Solution

#div1 {
      width: 400px;
      height: 200px;
      margin: 1em auto;
      border: 1px solid black;
      display: flex;
      align-items: center;       /* vertical center */
      justify-content: flex-end; /* far right */
}

#some_image {
     width: 50px;
      height: 25px;
}
<div id="div1">
  <img id="some_image" src="http://lorempixel.com/image_output/abstract-q-c-50-25-6.jpg">
</div>

Post Status

Asked in February 2016
Viewed 3,653 times
Voted 7
Answered 2 times

Search




Leave an answer