Use the Adjacent Sibling Combinator to Optionally Display Elements

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

The sibling combinators are a neat way to select elements that are siblings or descendants of siblings to checkboxes. It provides a way to show and hide elements without the need for JavaScript.

Instructor: [0:00] At this stage, our tic-tac-toe board is almost working. I've gone ahead and styled the board cells using the nested feature of stylus to size them to the right cell size and relative positioning.

[0:12] The labels are now also absolutely position and assume the height and width of the cell, but there's an issue. The overlays aren't blocking use of each cell. To fix this, we can set as an index of 2 on our overlays and now we can't click the labels.

[0:27] We only want to display the overlay for a cell that has been clicked. Let's start by setting a default of display none. To display an overlay for a cell, we can use the adjacent sibling combinator. Here we're saying select the div that's the adjacent sibling to an element that's in the checked state. Then we're going to set display: block.

[0:47] To make this easier to visualize, we're going to set a theme background on the board of hsla(, , 10, .1). We're going to remove the text for our labels and set some text for our overlays, so we have naught and cross.

[1:03] Now when we click a cell, we should see the correct overlay being shown. We can't re-click a cell to change its state. We can keep going until we fill up the board. The only way to reset the board state is to hit this Reset button or refresh the page.

[1:19] In review, we can use the adjacent sibling combinator to select an adjacent sibling. In this example, we're grabbing the overlay element that directly succeeds a checked checkbox.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today