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 4 years ago
Updated 4 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.