CSS Selectors — CSS Technical Interview Questions & Answers
Element, class, id, attribute and combinator selectors.
CSS Selectors
- Element, class, id, attribute and combinator selectors.
- Selectors pick elements: p (type), .card (class), #main (id), [type=email] (attribute), p:hover (pseudo). Combinators: .card p (descendant), .card > p (child).
- Specificity: id beats class beats type. Don’t fight with !important as a habit.
- Trap: #id for every style. Trap: spaces vs > vs + confused.
Technical Interview Tip: .card p { } descendant. #id is strongest common selector.
Code Examples for CSS Selectors
CSS Selectors — working example
/* element */ p { line-height: 1.6; color: #334155; }
/* class */ .title { font-weight: 700; }
/* id */ #main { max-width: 960px; }
/* attribute */ input[type="email"] { letter-spacing: 0.02em; }
/* descendant */ .menu li { margin: 0.25rem 0; }
/* child */ .menu > li { list-style: none; }
/* Specificity roughly: inline > id > class/attr/pseudo-class > element */
/* Inherited: color, font-*; Usually not: margin, padding, border */CSS Selectors — the cascade + specificity decide winners; some properties inherit (color/font), many layout ones do not.
How to Explain CSS Selectors to an Interviewer
Class vs id selector?
.card class #main id — more specific