2

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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    Partial/probable dupe: http://stackoverflow.com/questions/396145/how-to-vertically-center-a-div-for-all-browsers – Marc B Feb 08 '16 at 14:34
  • http://stackoverflow.com/questions/79461/vertical-alignment-of-elements-in-a-div – jumps4fun Feb 08 '16 at 14:35
  • css alignment is one of the most answered subject on stackoverflow. You should show us what alternatives you have already tried, and why other answers here on the site doesn't work in your case. – jumps4fun Feb 08 '16 at 14:37

2 Answers2

2

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>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
0

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>
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69