Quick CSS tips

1 min read
9/21/2022

Quick css tricks

Basic Combinators

<div  class="A">
	<span  class="B">one</span>
	<span  class="C">two</span>
	<span  class="B">three</span>
	<span  class="B">four</span>
	<div>
		<span  class="B">five</span>
	</div>
</div>
<span  class="B">six</span>

How selecting works with the css

/* Descendant: all .B elements inside .A */
/* one, three, four, five */
.A .B {
  color: red;
}

/* Child: all .B which are direct childs of .A x*/
/* one, three, four */
.A > .B {
  color: green;
}

/* Adjacent sibling: .B that follows immediately after .C */
/* three but overridden by ~ */
.C + .B {
  color: blue;
}

/* General sibling: all sibling .B that follows after .C */
/* three, four */
.C ~ .B {
  color: orange;
}

What it finally looks like:

onetwothreefour
five
six

Selecting custom attributes

Useful especially for templates (for assignment 2!)

<div class="pop-up" template>
	<h1 class="message">This is a pop up message</h1>
	<button>Exit<button/>
</div>

Selecting in css

[template] {
	background-color: red;
}

/* or if you wanted to be more specific */

.pop-up[template] {
	background-color: red;
}

If you wanted to select this in javascript

document.querySelector('.pop-up[template]');