CSS Alignment techniques – DEV Community

One widespread duties that’s requested typically in internet growth is to align components utilizing CSS, this may sound easy, however since there’s not one particular strategy to do it, it could develop into complicated.

I’ve put collectively a codepen collection to point out the completely different strategies.

Every codepen within the assortment exhibits a grid that represents a board that accommodates sticky-notes and the notes are displayed somewhere else of the board, like the next picture:

Alignment strategies:

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



Margin

Utilizing the margin attribute it’s straightforward to heart the weather horizontally, nevertheless, for vertical alignment you would need to calculate the peak or use the calc operate.

These are the properties wanted:

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

Or the shorthand property margin.

Right here is the codepen.



Line-height

Utilizing line-height will align the weather completely, nevertheless, if the textual content takes a couple of line of the aspect it will not match.

Properties wanted:

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

Right here is the codepen.



Desk-cell

Utilizing show: table-cell the vertical alignment will not be affected by font dimension or line peak, however as an obstacle this method solely applies to inline components.

Properties wanted:

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

Right here is the codepen.



Positions

This is among the commonest strategies used for positioning components

Properties wanted:

  • place: relative
  • place: absolute
  • prime
  • proper
  • backside
  • left
  • rework: translate(x, y)

Right here is the codepen.



Flex

The show: flex property was launched with CSS3 and makes quite simple and intuitive to align the weather, moreover this method is extra pleasant with completely different writing varieties, that is helpful if you’re seeking to present your web page in nations with completely different writing varieties.

Properties wanted for containers:

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

Right here is the codepen.



Conclusion

One of the best approach to use would rely in your use case and your web page’s structure.

Final however no least, the concept for this entry got here from the notes I took within the CSS Grid course on Platzi, that I extremely advocate should you communicate or perceive Spanish.

Add a Comment

Your email address will not be published. Required fields are marked *