I've been writing CSS for a while now, but I was always unclear as to why some of the rules I wrote did not target the element I intended for them to target - even though I was certain that I wrote them correctly. This was until I found a super easy trick in VS Code (Visual Studio Code) that put everything in perspective for me. Before we begin, a quick question. What is the difference between the two CSS selections below? If you don't understand, this post is for you.
div p.title-paragraph vs div p .title-paragraph
What does the space between selectors mean?
Let's begin with a simple definition that we'll build upon:
The space means that a child element should be selected.
Let's break this down: [code language="css"] div p.title-paragraph [/code] The rule above selects this: [code language="css"] [/code] Notice that the p tag is an element inside the div tag. Back to our simple definition: The space means that a child element should be selected. If we were to translate this rule into English, it would read: Select 'p' tags with the class 'title-paragraph' found inside a div - if a p tag is found inside a div, that makes it a child element. Let's move on to the second part of our example - what does: div p .title-paragraph mean? [code language="css"] div p .title-paragraph [/code] The rule above selects this: [code language="css"] <[any element] class='title-paragraph'> </ [any element]>; [/code] In this second example, the class (title-paragraph) does not belong to the p tag. Why? The space between the p and .title-paragraph (going back to our definition) denotes that a child element should be selected. In this case it's any child element with a class of '.title-paragraph' that this CSS selector will be targeting. If we were to translate this selector into English it would read: Select any element with the class 'title-paragraph' found inside a 'p' tag that is found inside a div. We are selecting any element because only the class is specified, not the element. Compare this example to the first.
VS Code makes it even easier to understand - see this super easy trick!
If you have Visual Studio Code installed, create or open a .CSS file. Make sure the file type is CSS in VS Code. In the CSS file, paste the following code (if you don't have any css written in that file). [code language="css"] div p.title-paragraph { } div p .title-paragraph { } [/code] Now, hover over the CSS selector and be amazed - it shows you exactly what your CSS targets. If you're ever writing CSS and unsure of what the outcome will be, place the selector in VS Code to verify your work.
The lesson here? Make sure you're writing code/css in a good code editor, they not only help you write better code, but they also help you understand what you're writing!