Introduction to CSS Selectors and Properties
CSS (Cascading Style Sheets) is the language that styles web content. CSS selectors target HTML elements for styling, while properties define how those elements should appear. Mastering CSS selectors and properties is essential for precise control over webpage appearance and responsive design.
Core CSS Concepts
- The CSS Rule:
selector { property: value; }
- Cascading: Styles can be inherited and overridden based on specificity and source order
- Specificity: Determines which styles take precedence when multiple rules target the same element
- Inheritance: Some properties are passed from parent to child elements
- Box Model: All HTML elements are boxes with content, padding, border, and margin
CSS Selectors by Type
Basic Selectors
Selector | Syntax | Description | Example |
---|---|---|---|
Universal | * | Selects all elements | * { margin: 0; } |
Type/Element | element | Selects all elements of specified type | p { color: blue; } |
Class | .classname | Selects elements with specified class | .highlight { background: yellow; } |
ID | #idname | Selects element with specified ID | #header { height: 80px; } |
Attribute | [attr] | Selects elements with specified attribute | [disabled] { opacity: 0.5; } |
Combinators
Selector | Syntax | Description | Example |
---|---|---|---|
Descendant | A B | Selects all B that are inside A | div p { line-height: 1.5; } |
Child | A > B | Selects all B that are direct children of A | ul > li { list-style: square; } |
Adjacent Sibling | A + B | Selects B immediately after A | h2 + p { font-weight: bold; } |
General Sibling | A ~ B | Selects all B that follow A | h2 ~ p { margin-left: 20px; } |
Pseudo-Classes
Selector | Description | Example |
---|---|---|
:hover | Element being hovered | a:hover { text-decoration: underline; } |
:active | Element being clicked | button:active { transform: scale(0.98); } |
:focus | Element with focus | input:focus { border-color: blue; } |
:first-child | First child of parent | li:first-child { font-weight: bold; } |
:last-child | Last child of parent | li:last-child { border-bottom: none; } |
:nth-child(n) | Nth child of parent | tr:nth-child(odd) { background: #f5f5f5; } |
:not() | Elements not matching | input:not([type="submit"]) { border: 1px solid #ccc; } |
Pseudo-Elements
Selector | Description | Example |
---|---|---|
::before | Creates content before element | p::before { content: "→ "; } |
::after | Creates content after element | a::after { content: " ↗"; } |
::first-letter | Selects first letter | p::first-letter { font-size: 2em; } |
::first-line | Selects first line | p::first-line { font-style: italic; } |
::selection | Selected text | ::selection { background: yellow; } |
CSS Properties by Category
Text Styling
Property | Description | Example Values |
---|---|---|
color | Text color | #333 , rgb(50, 50, 50) , blue |
font-family | Font typeface | Arial, sans-serif , "Times New Roman", serif |
font-size | Text size | 16px , 1.2em , 1.5rem , 120% |
font-weight | Text thickness | normal , bold , 600 |
font-style | Text style | normal , italic , oblique |
text-align | Horizontal alignment | left , right , center , justify |
text-decoration | Text decoration | none , underline , line-through |
text-transform | Capitalization | none , uppercase , lowercase , capitalize |
line-height | Line spacing | 1.5 , 20px , 150% |
letter-spacing | Character spacing | normal , 2px , -0.5px |
Box Model & Layout
Property | Description | Example Values |
---|---|---|
width | Element width | 300px , 50% , auto |
height | Element height | 100px , 50vh , auto |
padding | Inner spacing | 10px , 10px 20px , 10px 5px 15px 20px |
margin | Outer spacing | 10px , auto , 0 auto 20px |
border | Border around element | 1px solid black , 2px dashed red |
border-radius | Rounded corners | 5px , 50% |
box-sizing | How width/height are calculated | content-box , border-box |
display | Element display type | block , inline , flex , grid , none |
position | Positioning method | static , relative , absolute , fixed , sticky |
z-index | Stacking order | 1 , 100 , -1 |
Flexbox
Property | Description | Example Values |
---|---|---|
display | Enable flexbox | flex , inline-flex |
flex-direction | Direction of flex items | row , column , row-reverse , column-reverse |
justify-content | Align along main axis | flex-start , center , space-between , space-around |
align-items | Align along cross axis | stretch , center , flex-start , flex-end |
flex-wrap | Wrap items | nowrap , wrap , wrap-reverse |
flex | Shorthand for grow/shrink/basis | 1 , 1 0 auto , 0 1 200px |
gap | Space between flex items | 10px , 1rem , 10px 20px |
Grid
Property | Description | Example Values |
---|---|---|
display | Enable grid | grid , inline-grid |
grid-template-columns | Define columns | 100px 200px , 1fr 2fr , repeat(3, 1fr) |
grid-template-rows | Define rows | 50px auto , repeat(3, 100px) |
grid-column | Item column placement | 1 / 3 , span 2 |
grid-row | Item row placement | 2 / 4 , span 3 |
grid-gap | Space between grid items | 10px , 10px 20px |
grid-template-areas | Named grid areas | "header header" "sidebar content" |
Colors & Backgrounds
Property | Description | Example Values |
---|---|---|
background-color | Background color | #fff , rgba(255, 255, 255, 0.8) |
background-image | Background image | url('image.jpg') , linear-gradient(red, blue) |
background-size | Background image size | cover , contain , 100% 100% |
background-position | Background image position | center , top left , 50% 25% |
background-repeat | Background image repetition | repeat , no-repeat , repeat-x |
opacity | Element transparency | 1 , 0.5 , 0 |
Transitions & Animations
Property | Description | Example Values |
---|---|---|
transition | Property transition | all 0.3s ease , color 1s ease-in-out |
transform | Visual transformation | scale(1.5) , rotate(45deg) , translateX(10px) |
animation | Named animation | fadeIn 1s ease-in-out , bounce 2s infinite |
@keyframes | Define animation steps | @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } |
Selector Specificity
Selector Type | Specificity Value | Example |
---|---|---|
Inline styles | 1,0,0,0 | <div style="color: red;"> |
ID | 0,1,0,0 | #header |
Class, attribute, pseudo-class | 0,0,1,0 | .active , [type="text"] , :hover |
Element, pseudo-element | 0,0,0,1 | div , ::before |
Common CSS Challenges and Solutions
Challenge: Centering Elements
/* Horizontal centering for block elements */
.center-block {
margin: 0 auto;
width: [specific-width]; /* must have width */
}
/* Centering with flexbox (horizontal and vertical) */
.center-flex {
display: flex;
justify-content: center;
align-items: center;
}
/* Absolute positioning center */
.center-absolute {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Challenge: Creating Responsive Layouts
/* Mobile-first approach */
.container {
width: 100%;
padding: 15px;
}
/* Tablet and larger */
@media (min-width: 768px) {
.container {
width: 750px;
margin: 0 auto;
}
}
/* Desktop and larger */
@media (min-width: 1024px) {
.container {
width: 980px;
}
}
Challenge: Handling Text Overflow
/* Truncate with ellipsis */
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Wrap long words */
.word-wrap {
overflow-wrap: break-word;
word-wrap: break-word;
hyphens: auto;
}
CSS Best Practices
- Use a CSS Reset or Normalize.css to ensure consistent styling across browsers
- Follow a naming convention (BEM, SMACSS) for clearer, more maintainable code
- Minimize specificity to avoid complex overrides
- Group related properties for better readability
- Use shorthand properties when possible (
margin
,padding
,border
, etc.) - Comment your code for complex selectors or non-obvious styling choices
- Avoid
!important
except as a last resort - Utilize CSS variables (custom properties) for consistent theming
- Consider mobile-first design for responsive layouts
- Use relative units (
em
,rem
,%
,vh
,vw
) for responsive designs
Tools and Resources
CSS Frameworks and Libraries
- Bootstrap: Full-featured UI toolkit
- Tailwind CSS: Utility-first CSS framework
- Bulma: Modern CSS framework based on Flexbox
- Foundation: Responsive front-end framework
CSS Preprocessors
- Sass/SCSS: Extends CSS with variables, nesting, and more
- Less: Similar to Sass with a different syntax
- PostCSS: Tool for transforming CSS with JavaScript plugins
CSS Testing and Validation
- W3C CSS Validator: Check for CSS errors
- Can I Use: Browser compatibility tables
- CSS Lint: Identifies problematic patterns
Learning Resources
- MDN Web Docs: Comprehensive CSS documentation
- CSS-Tricks: Articles and guides on CSS techniques
- Flexbox Froggy: Interactive game to learn Flexbox
- Grid Garden: Interactive game to learn CSS Grid
- Codecademy CSS Courses: Structured learning paths
Remember that CSS is continuously evolving, with new selectors and properties being added. Stay updated with the latest specifications and browser implementations to take advantage of new features and improvements.