Explain Codes LogoExplain Codes Logo

Border style do not work with sticky position element

html
responsive-design
css
box-shadow
Alex KataevbyAlex Kataev·Oct 15, 2024
TLDR

Apply a pseudo-element as a workaround to persist the border of a sticky element.

.sticky-element::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border: 2px solid blue; /* Customize with your color preference! Who said programmers can't be design-savvy? */ pointer-events: none; z-index: -1; } .sticky-element { position: sticky; top: 0; /* As the famous saying goes, "Sticky without 'top' is like a programmer without coffee." */ background: white; /* As a good neighbor, let's blend in with the background elements. */ } .sticky-element-parent { position: relative; /* A gentle reminder: Anchor your ship before you set sail! */ }

Handling borders on sticky table headers

The table layout

To prevent sticky table headers from hiding or overlapping borders:

  • Utilize border-collapse: separate; on the table.
  • Make the borders prominent using border-top and border-bottom on <th> elements.
  • In lieu of borders, consider using box-shadow as a border substitute.

Code insights

table { border-collapse: separate; /* Divide and conquer, they said. It applies to table borders, too! */ border-spacing: 0; } th { position: sticky; top: 0; background-clip: padding-box; /* Border security at its finest! */ box-shadow: inset 0px 1px 0px 0px #000; /* As close to lifting weights as any programmer gets - with box shadows! */ } td:first-child, th:first-child { border-left: 2px solid blue; /* Like the first pancake, the first child gets special treatment. */ } .container { overflow: auto; /* We're all for freedom here, let's allow for some scrolling! */ }

Border Control: The Advanced Level

The box-shadow styling

Use box-shadow to create cool border effects on sticky table headers and cells.

Tackling browser-specific inconsistencies

For browsers like Firefox, where sticky positioning behaves weirdly, consider specific fixes like empty pseudo-elements and adjustments on background.

Crafty use of pseudo-elements

Create complex border effects using ::before or ::after pseudo-classes in tandem with absolute positioning.

Preserving borders during scrolls

If scroll interactions cause borders to vanish, use alternatives like outline and box-shadow to maintain the visual persistence of borders.