As a beginner to web development one of the things I found that I struggled to learn how to do was styling my web pages, namely positioning elements on the page. I found this to be particularly difficult due to the number of variables that determine the position of an element.
Position
For starters there is the position
attribute. This attribute determines how an element will be rendered relative to the entire page. By default position
is static
, which means the element is positioned according to the normal flow of the document. We can change position
to be relative
,absolute
,fixed
or sticky
.
relative
: the element is positioned according to the normal flow of the document and offset according totop
,left
,bottom
andright
.absolute
: the element is taken out of the normal document flow and no space is created for the element. The element is still positioned relative to its parent.fixed
: not only is the element taken out of the document flow and no space is created for the element, the element is positioned relative to the page, not the parent. The element also does not move on scroll.sticky
: similar tofixed
, though it differs in that the element will move on a scroll, but it will get stuck at the top of the screen.
Web Dev Simplified made a really nice YouTube video that explains the position
attribute very well and it is just under 10 minutes long!
Display
Ok so now that we understand position
we should probably take a look at display
. This attribute is very complicated and could use multiple articles to explain it fully! For beginner's sake the most three important keywords to look at are:
block
: the element generates a block element box and creates line breaks before and after the element in the normal flow. This means that your element(s) will be on their own line.inline
: the element does not generate a line break before or after itself, therefore the element(s) will be on the same line together.inline-block
: a mix ofinline
andblock
(exactly as one would expect), the element generates a block element box much like theblock
keyword, though unlikeblock
,inline-block
does not create line breaks before or after the element so that the element(s) are displayed neatly in boxes, all on the same line.
Margin vs. Padding
Additionally relevant to positioning elements in CSS is understanding the differences between margin
and padding
. margin
is the spacing between the element and the edge of the page. While, padding
refers to the spacing between the border your element and the content your element contains.
Conclusion
After learning these fundamentals of CSS I felt comfortable positioning any element in my document anywhere on the page. To be clear these will fundamentals alone will not make you an expert, but they will definitely help you achieve a nice looking web page!
Top comments (0)