I have a bootstrap grid and I am trying to center an image (200×100 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>
4
Answers
My favorite vertical alignment hack:
It uses
translateY
andtop
to sandwich an item into a container with unknown height. This requires IE10+.You have to go against bootstrap styling but than it works
Try this
Check example at CODEPEN
CSS:
You also need to make sure that parent div of that image has height greater than image height.