CSS Pitfalls: 5 Combinations to Avoid
Positioned and Non-Positioned Values: A Quick Review
To understand the common pitfalls, let’s first review positioned and non-positioned values. Positioned values include:
- absolute
- fixed
- relative
- sticky
Each has its own set of rules and behaviors, and understanding these differences is crucial to avoiding headaches down the line.
The Problem with Position: Static and Z-Index
One common issue arises when combining position: static with z-index. Since static elements are part of the normal document flow, they can’t be removed from that flow. This means that if you want an absolute child element to respect its parent’s position, you need to set a relative value on the parent first.
.parent {
  position: relative;
}
.child {
  position: absolute;
  z-index: 1;
}But what happens when you add z-index to the mix?
The Surprise with Position: Static and Top/Bottom/Left/Right
Another gotcha involves using position: static with top, bottom, left, or right. These properties are meant for repositioning elements, but they won’t work with static elements.
.element {
  position: static;
  top: 10px; /* won't work */
}And what about margin-top and its friends? Do they behave differently?
The Animation Conundrum: Position and Animation/Transition
Animations and transitions are meant to provide smooth transformations between styles. But what happens when you try to animate or transition an element’s position?
.element {
  position: absolute;
  transition: top 0.5s;
}
.element:hover {
  top: 20px;
}The answer might surprise you.
The Display Dilemma: Inline and Height/Width
Inline elements, like span and a, only take up as much space as they need, while block elements, like p and div, always start on a new line. But what happens when you try to set heights or widths on inline elements?
.inline-element {
  height: 20px; /* won't work */
  width: 100px; /* won't work */
}And how do display values like inline-block come into play?
The Flexbox Fiasco: Display Flex and Justify-Self
Finally, let’s talk about flexbox. When using display: flex, you might expect justify-self to work as intended. But, alas, it doesn’t.
.flex-container {
  display: flex;
}
.flex-item {
  justify-self: center; /* won't work */
}So, how do you achieve the desired layout?