Skip to main content

Top CSS Theory

What is CSS and what is it used for?​

CSS stands for Cascading Style Sheets, and it is a stylesheet language used to describe the presentation of a document written in HTML or XML. CSS is used to control the layout, colors, fonts, and overall visual appearance of web pages, making them more aesthetically pleasing and user-friendly. CSS allows developers to separate content (HTML) from presentation (CSS), making websites easier to maintain and modify. It can be applied inline, internally within the HTML, or externally through linked .css files, affecting multiple web pages at once.

Example:

Inline CSS: <div style="color: red;">This is red text</div>
Internal CSS:

<style>
div {
color: red;
}
</style>
<div>This is red text</div>

External CSS:

/* styles.css */ div { color: red; }

<link rel="stylesheet" href="styles.css" />
<div>This is red text</div>

Can you explain the CSS cascade and inheritance model?​

The CSS cascade determines how conflicting styles are resolved when multiple rules apply to the same element. The cascade considers three main factors:

  1. Origin of Styles: Styles can come from the browser's default settings (user agent), the user’s custom styles, or the author’s styles (those you write). Author styles have the highest priority, followed by user styles, and then user-agent styles.
  2. Specificity: More specific rules take precedence over less specific ones. Specificity is calculated based on the type of selectors used.
  3. Source Order: If specificity and importance are the same, the last declared style will be applied. Inheritance in CSS allows properties to be passed down from parent elements to child elements. For instance, if a parent element has a font-size of 16px, the child elements will inherit this size unless they have their own font-size defined.

Example:

body {
font-family: Arial, sans-serif; /* Inherited */
color: black; /* Inherited */
}

p {
font-size: 14px; /* Inherited by <em> inside <p> */
}

em {
color: red; /* Overrides inherited color */
}

What is specificity in CSS and how is it calculated?​

Specificity is a measure of how specific a CSS selector is. It determines which styles will be applied when multiple rules could apply to the same element. Specificity is calculated using four levels of selectors, with different values assigned based on their specificity:

  1. Inline styles (e.g., style="...") have the highest specificity (1,0,0,0).
  2. ID selectors (e.g., #id) have high specificity (0,1,0,0).
  3. Class selectors (e.g., .class), attribute selectors (e.g., [type="text"]), and pseudo-classes (e.g., :hover) have medium specificity (0,0,1,0).
  4. Type selectors (e.g., div, p) and pseudo-elements (e.g., ::before) have low specificity (0,0,0,1).
    The specificity of a selector is represented as a tuple of values (a,b,c,d), where each part of the tuple corresponds to the above categories. The specificity of the most specific rule determines which style is applied.

Example:

/* Specificity: (0,0,1,0) */
p {
color: blue;
}
/* Specificity: (0,0,2,0) */
p .highlight {
color: green;
}
/* Specificity: (0,1,0,0) */
#intro p {
color: red;
}

/* If a paragraph has class "highlight" inside an element with ID "intro",
it will be colored red due to the higher specificity of the #intro p selector. */

How do CSS selectors work? Provide examples of different types of selectors (classes, IDs, attributes, etc.)​

CSS selectors are patterns used to select and style HTML elements. There are several types of selectors, each with different specificity:

  1. Type Selector: Targets elements by their type (e.g., div, p, a).
div {
margin: 10px;
}
  1. Class Selector: Targets elements by their class attribute.
.button {
background-color: blue;
}
  1. ID Selector: Targets an element by its unique ID.
#header {
background-color: grey;
}
  1. Attribute Selector: Targets elements based on the presence or value of an attribute.
input[type="text"] {
border: 1px solid black;
}
  1. Pseudo-class Selector: Targets elements in a specific state.
a:hover {
color: red;
}
  1. Pseudo-element Selector: Targets specific parts of an element.
p::first-line {
font-weight: bold;
}
  1. Universal Selector: Targets all elements.
* {
box-sizing: border-box;
}
  1. Descendant Selector: Targets elements nested within another element.
div p {
color: green;
}
  1. Child Selector: Targets direct child elements.
div > p {
color: blue;
}
  1. Adjacent Sibling Selector: Targets elements immediately preceded by a certain element.
h1 + p {
margin-top: 0;
}

What are pseudo-classes and pseudo-elements? Give examples of their usage​

Pseudo-classes and pseudo-elements are special selectors in CSS that target elements based on their state or specific parts of elements.

Pseudo-classes: These apply styles based on the state of an element.

:hover applies styles when an element is hovered over by a mouse.

a:hover { color: orange; }


:nth-child(n) applies styles to the nth child of a parent element.

li:nth-child(2) { background-color: yellow; }

Pseudo-elements: These style specific parts of an element.

::before inserts content before the content of an element.

p::before { content: "Note: "; font-weight: bold; }


::after inserts content after the content of an element.

p::after { content: " (end of paragraph)"; font-style: italic; }


::first-letter styles the first letter of an element.

p::first-letter { font-size: 2em; color: blue; }


::first-line styles the first line of an element.

p::first-line { font-weight: bold; }

How does the box model work in CSS?​

The CSS box model is a fundamental concept that defines how elements are sized and spaced on a web page. It consists of four parts:

  1. Content Box: The area where your content (text, images, etc.) is displayed.
  2. Padding: The space between the content and the border. Padding adds space inside the element.
  3. Border: A line that surrounds the padding and content. The border can be styled in terms of width, color, and style (solid, dotted, etc.).
  4. Margin: The space outside the border that separates the element from other elements on the page.
    Example:
div {
width: 200px;
padding: 20px;
border: 10px solid black;
margin: 15px;
}

In this example, the total width of the div element will be 200px (content) + 40px (padding, 20px on each side) + 20px (border, 10px on each side) + 30px (margin, 15px on each side) = 290px.

How to implement responsive design using media queries?​

Responsive design aims to make web pages look good on all devices by using flexible layouts, images, and CSS media queries. Media queries allow you to apply CSS rules based on conditions like screen width, height, orientation, and resolution. This way, you can tailor the design to different devices such as smartphones, tablets, and desktops.

Example:

/* Mobile styles */
body {
font-size: 16px;
}

@media (min-width: 768px) {
/* Tablet styles */
body {
font-size: 18px;
}
}

@media (min-width: 1024px) {
/* Desktop styles */
body {
font-size: 20px;
}
}

This example adjusts the font size based on the screen width: 16px for mobile, 18px for tablets, and 20px for desktops.

What are floats and how are they used in CSS?​

Floats are a CSS property that allows elements to be taken out of the normal document flow and positioned to the left or right of their container. Floated elements are aligned horizontally, and the content flows around them.

Example:

img {
float: left;
margin-right: 10px;
}

In this example, an image will float to the left, and the surrounding text will wrap around it.

How to center elements horizontally and vertically in CSS? Provide examples of different approaches​

Centering elements in CSS can be done in various ways, depending on whether you're centering inline elements, block elements, or using modern CSS techniques like Flexbox or Grid.

Horizontal centering with text-align:

.centered-text {
text-align: center;
}

Horizontal centering with margin: auto:

.centered-block {
width: 50%;
margin: 0 auto;
}

Vertical and horizontal centering with Flexbox:

.centered-flex {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

Vertical and horizontal centering with Grid:

.centered-grid {
display: grid;
place-items: center;
height: 100vh;
}

Vertical centering with absolute positioning:

.centered-absolute {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

What are CSS preprocessors (e.g., SASS, LESS) and what benefits do they offer?​

CSS preprocessors like SASS (Syntactically Awesome Style Sheets) and LESS (Leaner Style Sheets) are tools that extend CSS with additional features such as variables, nested rules, mixins, functions, and mathematical operations. Preprocessors are compiled into standard CSS before being used in a web page.

Benefits:

Variables: Store reusable values like colors or font sizes.

$primary-color: #333;

body {
color: $primary-color;
}

Nesting: Organize CSS in a nested hierarchy.

nav {
ul {
margin: 0;
padding: 0;

li {
display: inline-block;
}
}
}

Mixins: Create reusable blocks of code.

@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}

.box {
@include border-radius(10px);
}

Functions: Perform operations like calculations.

$width: 600px;

.container {
width: $width / 2;
}

How to use variables in CSS? Provide examples of CSS variable usage​

CSS variables, also known as custom properties, allow you to define values that can be reused throughout your stylesheet. They are defined with a -- prefix and accessed with the var() function.

Example:

:root {
--primary-color: #4caf50;
--secondary-color: #8bc34a;
--padding-size: 16px;
}

body {
background-color: var(--primary-color);
color: var(--secondary-color);
padding: var(--padding-size);
}

This example defines three variables (--primary-color, --secondary-color, --padding-size) and applies them to the body element.

What are cascade layers in CSS and how are they used?​

Cascade layers in CSS provide an additional layer of control over how styles are applied, similar to the cascade. Cascade layers allow you to group related styles and control their priority. Styles within a higher-priority layer override those in a lower-priority layer.

Example:

@layer base {
p {
color: black;
}
}

@layer theme {
p {
color: white;
}
}

@import url("theme.css") layer(theme);
@import url("base.css") layer(base);

In this example, styles in the theme layer will override those in the base layer because theme is declared later.

How to improve CSS performance on a web page? Provide examples of optimization techniques​

Improving CSS performance ensures faster loading times and a better user experience. Here are some techniques:

  1. Minimize CSS Files: Use minified CSS to reduce file size and decrease load times.
  • Use tools like CSSNano or UglifyCSS to minify your CSS files.
  1. Remove Unused CSS: Identify and remove unused CSS rules to reduce file size.
  • Tools like PurgeCSS can help automatically remove unused CSS.
  1. Use Efficient Selectors: Avoid deep nested selectors as they are more computationally expensive.
  • Prefer simple, flat selectors over deeply nested ones.
  1. Combine and Reduce HTTP Requests: Use CSS sprites or combine small images into one file to reduce HTTP requests.

CSS Sprite Example:

.icon {
background-image: url("sprite.png");
}

.icon-home {
background-position: 0 0;
}

.icon-user {
background-position: -20px 0;
}
  1. Use will-change Sparingly: This property is useful but can consume a lot of memory if overused, so apply it only when necessary.

  2. Use Modern Layout Techniques: Leverage CSS Grid and Flexbox for layouts instead of older methods like floats and inline-block, which can result in cleaner, more efficient code.

  3. Reduce Repaints and Reflows: Minimize changes to the DOM and styles that trigger layout recalculations, which are costly in terms of performance.

Implementing these techniques can significantly enhance the performance and maintainability of your CSS code, leading to faster load times and a smoother user experience.