Selectors and Properties

Understanding CSS selectors and how to apply styles


CSS Selectors and Properties

CSS selectors target HTML elements so you can apply styles to them.

Adding CSS to HTML

There are three ways to add CSS:

<!-- 1. External stylesheet (recommended) -->
<link rel="stylesheet" href="styles.css">

<!-- 2. Internal styles -->
<style>
    h1 { color: blue; }
</style>

<!-- 3. Inline styles (avoid) -->
<p style="color: red;">Red text</p>
HTML

Basic Selectors

/* Element selector - targets all <p> elements */
p {
    color: #333;
}

/* Class selector - targets elements with class="highlight" */
.highlight {
    background-color: yellow;
}

/* ID selector - targets the element with id="header" */
#header {
    font-size: 2rem;
}

/* Universal selector - targets everything */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
CSS

Combinators

/* Descendant: any <p> inside <article> */
article p {
    line-height: 1.8;
}

/* Child: direct <li> children of <ul> only */
ul > li {
    list-style: square;
}

/* Adjacent sibling: <p> immediately after <h2> */
h2 + p {
    font-size: 1.1rem;
}

/* General sibling: all <p> after <h2> */
h2 ~ p {
    color: #555;
}
CSS

Attribute Selectors

/* Has the attribute */
[disabled] {
    opacity: 0.5;
}

/* Attribute equals value */
[type="email"] {
    border-color: blue;
}

/* Attribute starts with */
[href^="https"] {
    color: green;
}

/* Attribute ends with */
[src$=".png"] {
    border: 1px solid #ccc;
}
CSS

Pseudo-Classes

a:hover { color: red; }
a:visited { color: purple; }
input:focus { outline: 2px solid blue; }
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
tr:nth-child(even) { background: #f5f5f5; }
input:required { border-left: 3px solid red; }
CSS

Specificity

CSS specificity determines which rule wins when multiple rules target the same element:

Selector Specificity Score
* Lowest 0,0,0
p Element 0,0,1
.class Class 0,1,0
#id ID 1,0,0
style="" Inline Highest