Julian Julian - 2 months ago 13
CSS Question

Vertical alignment of an image in a Twitter Bootstrap cell (height is unknown)

I have a bootstrap grid and I am trying to center an image (200x100 per example provided) inside a cell.



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row" style="border:1px solid red;">
<div class="col-xs-6">
some text<br />
some text<br />
some text<br />
some text<br />
</div>
<div class="col-xs-6">
some text<br />
some text<br />
some text<br />
some text<br />
</div>
</div>
<div class="row" style="border:1px solid red;">
<div class="col-xs-6">
<img src="http://placehold.it/350x150">
</div>
<div class="col-xs-6 container">
<img class="img" src="http://placehold.it/200x100">
</div>
</div>
</div>
</body>
</html>





I've tried a lot of techniques provided on internet without any luck. (BTW most of them explicitly define a height) As a proof I provide some of them here:

Example1: a trick with padding-top: 100% increases a row which I do not need.

Example2: table/table-cell just not working

Example 3: a trick with inline-block and vertical align is not working

<style>
.container:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}

img {
display: inline-block;
vertical-align: middle;
}
</style>


Example 4: absolute position with top, left 50% and translate is working wrong

<style>
.img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>

Answer

Try this

Check example at CODEPEN

CSS:

.row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  flex-wrap: wrap;
}

.row > [class*='col-'] {
  display: flex;
  flex-direction: column;
  align-self: center;
}

.row > [class*='col-'] img {
  align-self: center;
}