DEV Community

David
David

Posted on

CSS Alignment techniques

CSS Alignment techniques

One common tasks that is requested often in web development is to align elements using CSS, this might sound simple, but since there is not one specific way to do it, it can become confusing.

I have put together a codepen collection to show the different techniques.

Each codepen in the collection shows a grid that represents a board that contains sticky-notes and the notes are displayed in different places of the board, like the following image:

final design

Alignment techniques:

  • Margin
  • Line-height
  • Table-cell
  • Positions
  • Flex

Margin

Using the margin attribute it is easy to center the elements horizontally, however, for vertical alignment you would have to calculate the height or use the calc function.

These are the properties needed:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

Or the shorthand property margin.

Here is the codepen.

Line-height

Using line-height will align the elements perfectly, however, if the text takes more than one line of the element it won't fit.

Properties needed:

  • text-align -> For horizontal alignment.
  • vertical-align -> For vertical alignment.
  • line-height -> defines the size of the line.

Here is the codepen.

Table-cell

Using display: table-cell the vertical alignment is not affected by font size or line height, but as a disadvantage this technique only applies to inline elements.

Properties needed:

  • display: table-cell
  • text-align
  • vertical-align

Here is the codepen.

Positions

This is one of the most common techniques used for positioning elements

Properties needed:

  • position: relative
  • position: absolute
  • top
  • right
  • bottom
  • left
  • transform: translate(x, y)

Here is the codepen.

Flex

The display: flex property was introduced with CSS3 and makes very simple and intuitive to align the elements, additionally this technique is more friendly with different writing forms, this is useful if you are looking to show your page in countries with different writing forms.

Properties needed for containers:

  • display: flex
  • justify-content
  • align-items

Here is the codepen.

Conclusion

The best technique to apply would depend on your use case and your page's architecture.

Last but no least, the idea for this entry came from the notes I took in the CSS Grid course on Platzi, that I highly recommend if you speak or understand Spanish.

Discussion (0)