Stupid CSS Tricks

I’ve been meaning to share a couple of tricks I’ve been using over the past few years. Here are some that might be useful. I haven’t seen these techniques mentioned many times elsewhere.

Easy Vertical Centering

There are many ways to accomplish vertical centering with CSS. None of them are as intuitive as the days of table-based layouts - not that we actually miss those days - but I found a trick a while back using margin: auto when an element is absolutely positioned with top / right / bottom / left all set to zero. You can write a mixin like this:

@mixin centered() {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}

Check out the CodePen example.

Responsive Offset Images

Not necessarily something new but a while back, I needed to come up with a method for offsetting transparent images while allowing them to scale responsively. I wrote a mixin to handle the offset:

/*
Adding this to a wrapper element around an `img`
will create a top or bottom offset that will be
maintained in a responsive container. Defaults
to a bottom offset. Add `.top` for a top offset.

arguments: $width, $height, $offset
example:   @include offset_image(225, 440, 80);

*/

@mixin offset_image($width, $height, $offset: 0) {
  padding-top: percentage(($height - $offset) / $width);
  position: relative;
  width: 100%;
  height: auto;
  z-index: 1;

  img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: auto;
  }

  &.top {

    img {
      top: auto;
      bottom: 0;
    }
  }
}

Check out the CodePen example.

Centered Background Video

In the past it’s been really hard to center images and video in the background. This technique can be used on any element but is most useful for images and videos. I’m not a big fan of using video backgrounds on websites for performance reasons, but when you have to do it, this will prevent you from having to resort to JavaScript for scaling and positioning. Here’s an example for video:

.video {
  display: block;
  position: absolute;
  z-index: 0;
  width: 100%;
  height: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  margin: auto;

  @media screen and (max-aspect-ratio: 239/100) {
    width: auto;
    height: 100%;
  }
}

It’s worth noting that max-aspect-ratio can’t take decimals. This chart may be helpful too.

Check out the CodePen example.