Aligning Elements on a Page | Vertically & Horizontally

Before aligning an element on a page, you should be clear about one thing: is it an inline or block level element. This will determine how the element will behave. Some examples of block-level elements include: div, aside, section, footer, h1 - h6, form and nav; there are many more. These elements take up the full width of space available (sometimes that is the full width of the screen).

In the following example, the div is positioned in relation to the container element it is housed within. The top of the element is then pushed halfway down the page, from the top of the container element (so the entire div sits just below the center horizontal line). translateY changes the position of an element along the Y-axis. In this case, it pulls the div halfway back up  (hence the negative number) .

div {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

To center the div horizontally on the page, again make sure you're manipulating a block level element. Give it a width; this can be a hard pixel number or percentage of the overall width. Set the left and right margins to auto. The div will take up the space you've determined and split the remaining white space evenly between the two margins.

div {
  width: 25%;
  margin: auto;
}

There you have it, now you can simply, and with very little code position elements exactly where you'd like them on the web page.