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 {
 border: 1px solid #587cdd; 
 border-radius: 5px; 
 margin: 5px;
 width: 50px; height: 50px;
 text-align: center;
 position: relative;
 float: left;
 -webkit-transform-style: preserve-3d;
 -moz-transform-style: preserve-3d;
 ransform-style: preserve-3d;
.content {
 position: absolute; 
 top: 50%; 
 -webkit-transform: translateY(-50%);
 -ms-transform: translateY(-50%);
 transform: translateY(-50%); 
 display: block; 
 width: 100%;

<script src=""></script>

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

new Vue({
 el: '#app',

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

No comments: