CSS for the XAML Guy - Positional Selectors


AngleBracketsI got into a longish, public discussion last night about XAML versus the HTML/CSS stack last night. I think they both have merit and pros and cons but it made me decide to add a short series of posts that highlight some of the CSS things that surprised me most (like my JavaScript for the C# Guy posts - and yes, more of those are coming too).

The first topic I am covering is some subtleties of the selector syntax. CSS selectors allow you to pick children, descendants and adjacent siblings. I found that I used descendant selector quite a lot:

#main h1 /* descendant */
{
  color: Red;
}

This syntax effectively says, any h1 inside an element named "main". I see people assume this actually means, *directly* inside the "main" element. So if you had some HTML like this, all h1's inside "main" would be colored red:

<!DOCTYPE html>
<html>
<body>
  <h1>Top</h1>
  <section id="main">
    <h1>Main Level</h1>
    <section id="article">
      <h1>Second Level</h1>
      <p>Yup</p>
    </section>
  </section>
</body>
</html>

Note that it applies to all the descendants. But but if you did want just the h1's directly inside (or...ahem a child) of "main"? That's child selector syntax:

#main > h1 /* child */
{
  font-size: 24px;
}

Then only the h1 containing "Main Level" will have the rule applied. I've seem some CSS with tons of "!important" to override the descendant syntax because they didn't seem to know about child selector. 

The last one is the adjacent sibling selector. This selector looks for elements that are directly next to each other (or...ahem...adjacent):

h1 + p /* adjacent siblings */
{
  border-bottom: black 2px solid;
}

In this case, the p (not the h1) will have a border under it. The other h1's will be left unmolested. Here's a complete example if you want to play:

"If you're not careful, you just mind learn something..."


Ready to Learn Vue with ASP.NET Core?

My new Wilder Minds' course is available as an Early Access for only $79. It will be released on a weekly basis. The first module is now available:

Enroll Today


Shawn
Shawn Wildermuth
Author, Teacher, and Coach




My Courses

Wilder Minds Training
Vue.js by Example (Now Available)
Bootstrap 4 by Example
Intro to Font Awesome 5 (Free Course)
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.1)
Using Visual Studio Code for ASP.NET Core Projects
Implementing ASP.NET Web API
Web API Design
JavaScript for C# Developers

Application Name WilderBlog Environment Name Production
Application Ver v4.0.30319 Runtime Framework x86
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26725.06
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86