HTML Element Style How to - Align Image in center of div unknown height width








Question

We would like to know how to align Image in center of div unknown height width.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.slider {<!--from   w  w  w . j  av  a2  s  .c  o m-->
  width: 100%;
  position: relative;
  text-align: center;
  height: 400px;
}

.slider:before {
  height: inherit;
  display: inline-block;
  vertical-align: middle;
  content: "";
}

.center {
  display: inline-block;
  margin: auto;
  vertical-align: middle;
}
</style>
</head>
<body>
  <div class="slider">
    <img class="center" src="http://www.placehold.it/100x40" />
  </div>
</body>
</html>

The code above is rendered as follows: