DEV Community

David
David

Posted on • Updated on

CSS Alignment techniques

CSS Alignment techniques

One common task that is frequently requested in web development is aligning elements using CSS. While this may sound simple, it can become confusing due to the absence of a single specific way to achieve it.

I have curated a CodePen collection to demonstrate various alignment techniques.

Each CodePen in the collection showcases a grid representing a board containing sticky notes. The notes are displayed in different positions on the board, as shown in the following image:

Final design

Alignment Techniques

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

Margin

Using the margin property, it is easy to horizontally center the elements. However, for vertical alignment, you would need to calculate the height or use the calc function.

The required properties are as follows:

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

Alternatively, you can use the shorthand property margin.

Here is the corresponding CodePen.

Line-height

Using line-height allows for precise alignment of elements. However, if the text spans multiple lines within the element, it may not fit perfectly.

The required properties are:

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

Here is the corresponding CodePen.

Table-cell

Using display: table-cell, the vertical alignment is unaffected by font size or line height. However, this technique only applies to inline elements.

The required properties are:

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

Here is the corresponding CodePen.

Positions

This is one of the most commonly used techniques for positioning elements.

The required properties are:

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

Here is the corresponding CodePen.

Flex

The display: flex property, introduced with CSS3, makes it incredibly simple and intuitive to align elements. Additionally, this technique is more accommodating for different writing systems, which is useful if you intend to display your page in countries with diverse writing forms.

The required properties for containers are:

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

Here is the corresponding CodePen.

Conclusion

The best technique to employ will depend on your specific use case and page architecture.

Last but not least, the inspiration for this article came from the notes I took during the CSS Grid course on Platzi, which I highly recommend for Spanish speakers or those who understand Spanish.

Top comments (0)