CSS Tricks to Center Absolutely Positioned Elements of Variable Height

CSS Tricks to Center Absolutely Positioned Elements of Variable Height

CSSThese are some really clever solutions prompted by a discussion on the Front End Developers Group in LinkedIn

Question posed:

Have you ever needed to centralize an absolute element (horizontal and vertical), but the height was variable?

Some really interesting solutions  and the browser support for each one. I list a few of the tried and tested methods at the end.

Solution One:

On Code Pen: http://codepen.io/LFeh/pen/LFHBG. This is not100% supported in versions IE 8 and below, so use your best judgement:

the HTML:


<div class="center centerALL">
<div class="inner">You can also position your element only in the vertical or horizontal. This work in IE6+</div>
</div>

the CSS:

 

// Translate mixin
// ------------------------------
.translate(@x; @y) {
  -webkit-transform: translate(@x, @y);
      -ms-transform: translate(@x, @y); 
       -o-transform: translate(@x, @y);
          transform: translate(@x, @y);
}

// Center-align mixin
// ------------------------------

// Center full
.center-full() {
  position: absolute;
  top: 50%; left: 50%;
  .translate(-50%, -50%);
}

// Center top only
.center-top() {
  position: absolute;
  top: 50%; 
  .translate(0, -50%);
}

// Block element
// ------------------------------

.box {
  border: darken(#428bca, 10%) solid 1px;
  .center-full();
  color: #222;
  font-size: 26px;
  font-family: arial;
  height: 50%;
  padding: 20px;
  width: 50%;

  p {
    .center-top();
  }
}

Basically, this behaves much like the table layout trick:

position: absolute; #top: 50%;display: table-cell; vertical-align: middle;"

Solution Two:

This one is supported in both IE6 and IE8: http://codepen.io/anon/pen/fGpBu

The HTML:

<div class="center centerALL">
<div class="inner">You can also position your element only in the vertical or horizontal. This work in IE6+</div>
</div>

The CSS:

body{
                font-family:verdana;
            }
            .center{
                height:50%;
                width:50%;
                background-color: gainsboro;
                position:absolute;
                display:table;
            }
            .centerV {
                top : 25%;
            }
            .centerO {
                left:25%;
            }
            .centerALL{
                top:25%;
                left:25%;
            }
            .center .inner{
                padding:50px;
                display:table-cell;
                vertical-align:middle;
            }

Other solutions:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top