Consider a scenario, where you're asked to design a **
Stack
** layout, something similar to the below one.
Normally as a **
WEB DEVELOPER
** :sweat_smile: we will try this,
<style>
.stack {
background-color: yellow;
}
.stack > div {
margin-bottom: 40px;
}
</style>
We will wrap the three text divs with a common
div
and apply
margin-bottom
to all its' children. As of now we will be happy with our implementation, thinking how great we are :sweat_smile: that the STACK layout is done in a matter of minutes.
However, this will be our output :weary:
If you closely see the image, you will notice the third text div also has the
margin-bottom
style applied on it, which we don't want to happen.
We will try to fix the breakage by doing something similar to this,
<style>
.stack > div:last-child {
margin-bottom: 0px;
}
</style>
We will reach our destination, but the path we took... isn't it ugly? :mask:
While thinking of other possibilities, I came across (* + *), a construct known as the **
Owl
** and its' powers. But the only thing to note is that the 🦉 is little mysterious!. No worries though, let's clear up the mystery behind and unveil its' greatest powers down here...
The 'Owl' construct selects 'any HTML element that is next to or follows(sibling) any other HTML element' booyah :sweat_smile:
Come lets' smash out the theory, get hands-on with the 🦉
Consider the same snippet updated with,
<style>
.stack {
background-color: yellow;
}
.stack > *+* {
margin-top: 1.5em;
}
</style>
Boom :boom: that's it! This is much simple compared to our old prototypes.
Now the path we took was very clear and really beautiful :heart_eyes:,
Now lets' dig on to check out what it does underhood :mag:
Digging the snippet we come to know that the **
Owl
** construct selects the 2nd and 3rd child and applies margin-top: 1.5em respectively as defined. It doesn't select the first child because, it is an immediate successor of the parent and doesn't have any previous siblings(general behaviour of '+' selector).
Now, I doubted the layout in case of nested HTML elements, an evil thought though :alien:, something more specifically like :point_down:
<div class="stack">
<div>
...
<div class="inner-div">
<div>
...
</div>
<div>
...
</div>
</div>
...
</div>
<div>
...
</div>
<div>
...
</div>
</div>
Using our existing style definitions, The inner divs have no margins. The layout obtained is :point_down:
Oops what to do now, scratched my head a lil' bit and just removed the Child combinator preceding our **
Owl
** construct.
<style>
.stack {
background-color: yellow;
}
.stack *+* {
margin-top: 1.5em;
}
</style>
The output obtained is :tada:
So, what the previous snippet does is that, it applies the 'Owl' construct recursively to all descendants not limiting only to the direct children of parent div element.
Hope, you guys figured out the **
Owl
** construct with this post. Thanks for being patient till the end fellas! :satisfied: