CSS Cookbook

Horizontally center an absolutely-positioned element

.element {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
  width: 400px;
}
  • In our code, left: 50%; will align the element's left edge to the horizontal axis of the parent container
  • Then, transform: translate(-50%, 0); will further move the element to the left, effectively centering it on the parent's horizontal axis. See a live demo on Codepen.
  • Notice we could also obtain the same result w/ margin-left: <negative half the width of the element>;

Absolutely center an element

.element {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;

Create image-replaced elements -- like a nav logo

Given this portion of a webpage:

<header>
  <h1><a class="logo" href="#">Sven's Snowshoe Emporium</a></h1>
  <h2>"For the Snow-Savvy Shoe-Shopper"</h2>
</header>
  • we can create a linked logo by assigning a bg image to an <a> elem
  • notice we also need some fallback text, in case the .logo class fails to load
  • anyway, in order to hide the text when viewing the page in normal conditions, we have to push it out of the viewport with the text-indent property
.logo {
  background: url(logo.png);
  display: block;
  height: 75px;
  width: 250px;
  text-indent: -9999px;
}

Make the footer stick to the bottom of an empty page

Assuming this page structure:

<html>
  <head></head>

  <body>
    <header></header>
    <main></main>
    <footer></footer>
  </body>
</html>

Using Flexbox, we'll set body as a flex container and:

body {
  display: flex;
  flex-flow: column nowrap;
  min-height: 100vh;
}

main {flex: 1;}

This way main will take all the available residual space after <header> and <footer> are laid out, so the footer will stick to the bottom of the page.


Normalize the browser's default font sizes

/*
with this reset we can normalize the browser's default font sizes,
and then override them with our styles
*/

body {
  font: inherit;
  font-size: 100%;
}