Saturday, July 29, 2017

"vertical-align: middle" that works anywhere

Outside a table cell, vertical-align: middle does not work as expected. The following is a css that allows any child element to be positioned at center vertically and horizontally.

text-align: center works in most cases. However, it does not place a child element in perfect center position. It generally places the left-most edge of child element to the center horizontally, giving the look of off-to-right appearance of the child element.

.cell {
 position: relative;
 border: 1px solid #587cdd; 
 border-radius: 5px; 
 margin: 5px;
 width: 50px; 
 height: 50px;
 text-align: center;
 float: left;
 -webkit-transform-style: preserve-3d;
 -moz-transform-style: preserve-3d;
 ransform-style: preserve-3d;
}
.content {
 position: absolute; 
 top: 50%; 
 left: 50%;
 transform: translate(-50%, -50%); 
 -webkit-transform: translate(-50%, -50%);
 -ms-transform: translate(-50%, -50%);
}

<script src="https://unpkg.com/vue"></script>

<div id="app">
 <span class="cell" v-for="n in 10">
  <span class="content">{{ n }}</span>
 </span>
</div>

new Vue({
 el: '#app',
 
});

The above code will produce the following. Each square has content with dead center position: both horizontally and vertically.