I have been dabbling in CSS on and off for some years now, and layouts is something I still don't feel confident about. Flex and Grid have, without doubt, alleviated layout woes. Yet, that's only one facet of component layout.
One of the main issues I have with CSS is that layout declarations feel hit-or-miss. The same declaration works at time, and fails at others. I am pretty familiar with display, position, z-index and yet, they work as expected only about 90% of the time.
The 10% of the time it doesn’t, mostly the same routine plays out: I try debugging my code — get frustrated — give up — end up on StackOverflow — find an arbitrary ‘hack’ - look that details of the hack on mdn to find a seemingly random CSS rule!
Depending on the rule, I have a solution to my problem, or I rethink my approach. In either case, I end up with more additions to my prized bag of CSS ‘tricks’, and a stronger conviction that CSS rules are as arbitrary as ones of English language.
Repetitive outcomes highlight patterns. In this case, I realized most of the non-obvious ‘corner’ cases were due to a) “side-effects” of some CSS properties and/or b) meld of multiple properties (ex: interaction of z-index & transform).
So, I decided to dig deeper into the interplay of CSS concepts and properties which affect layout of an element. This article is a summary of what I have learned (till now).
I am mostly writing this for my future self. This may be useful to you if are also interested in digging into core CSS concepts, or looking for a cheat-sheet to debug your CSS (the ‘Be aware of’ section may work as a quick checklist).
It may not pertinent to a CSS beginner. (The assumption is you are familiar with DOM structure, and basic CSS concepts — syntax, specificity, cascades, inheritance).
Primarily, layout of an element encapsulates two factors - size of an element and its position on the screen (x-, y- & z-axis). These factors are affected by the contents of the element as well as its relationship to other elements.
The sum and substance of my understanding can be boiled down to 3 simple points:
- Every element is a box — the content and the element type defines the default size and layout
- The position & size of the box may be dependent on ‘outer’ boxes within which they are nested
- The ‘outer’ box is not always the parent element
I will zoom into an element to look into i) its layout properties, ii) what its "outer" box is and how that is determined and iii) how that affects its layout. Each topic will be followed by a list of its commonly overpassed corollaries in the 'Be aware of' section.
I will touch upon the following topics (with varying depths):
- The element box
- Box Model
- Block & Inline Elements
- CSS Flow, Positioning & Floats
- The outer box
- Containing Block
- Formatting Context
- Stacking Context