Center and size an absolutely positioned box with percentages only

in code


I feel like I have been screwed over with lightheadedness lately, so let’s see if I can churn out something useful. There are times when you have to absolutely position a child element, and there are subset of those cases where the child has to be positioned absolutely in the center of the parent. The common piece of advice given is to use a fixed size negative margin, thus:

.foo {
    left: 50%;
    margin-left: -100px; 
    position: absolute;
    top: 30px;
    width: 200px;
}

That’s always bugged me. What if I need a flexible width, but don’t want to use JavaScript? Huzzah for the CSS3 transform property:

.foo {
    left: 50%;
    position: absolute;
    transform: translateX(-50%);
    width: 30%;
}

To take this a half-step further, I wanted a responsive flex height too, proportional to its width:

.foo {
    height: 0;
    padding-bottom: 30%;
    width: 30%;
}

In the above, the padding-bottom attribute is equal to the width, so:

  • padding-bottom: 30%; == “100% of the width”
  • padding-bottom: 60% == “200% of the width”
  • padding-bottom: 15% == “50% of the width”

And so on. This even works for anchor elements, in instances where you want a responsive button size without a fixed width:

a.foo {
    display: block;
    height: 0;
    padding-bottom: 100%;
    width: 100%;
}

You can play around with this on JSFiddle (using viewport units). Sass mixin:

@mixin flex_size($width, $ratio) {
    // Ratio should be between 0 and foo.
    display: block;
    height: 0;
    padding-bottom: $width * $ratio;
    width: $width;
}


Decompression

in me


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