CSS Interview Questions


CSS Interview Questions

 

What is CSS?

CSS stands for Cascading Style Sheets. It is a stylesheet language used to describe the presentation of a document written in HTML or XML. CSS controls the layout of multiple web pages all at once.

What are the different types of CSS?

  • Inline CSS: Applied directly within an HTML element using the style attribute. It provides styling for a specific element on a single instance basis.
  • Internal CSS: Defined within a <style> tag in the <head> section of an HTML document. It applies styles to the entire document or specific elements within it.
  • External CSS: Written in a separate .css file and linked to HTML documents using the <link> tag. It enables consistent styling across multiple pages of a website and promotes easier maintenance and scalability.
  • CSS Frameworks: Pre-prepared collections of CSS files that provide standardized styling for web components and layouts. Frameworks like Bootstrap and Foundation expedite development by offering pre-designed styles and responsive layouts.
  • CSS Preprocessors: Extensions of CSS that allow for more efficient and maintainable stylesheets. Preprocessors like Sass and LESS introduce features such as variables, nesting, and mixins, enhancing the capabilities of standard CSS.

What is the box model in CSS?

The box model represents the structure of a web page element. This model allows us to create design and layout for HTML elements.

  • Content: This is the actual stuff inside the box, like text or images.
  • Padding: This is the space between the content and the edge of the box. It's like a cushion around the content.
  • Border: This is the line that goes around the padding. It's like a frame around the content and padding.
  • Margin: This is the space between the border of this box and other boxes around it. It's like the empty space between this box and its neighbors.

Explain the CSS specificity hierarchy.

Specificity determines which CSS rule is applied by the browser when multiple rules match the same element. It follows this order:

  • Inline Styles: These are styles applied directly to an HTML element using the style attribute. They have the highest specificity because they are right there in the HTML.
  • IDs: If you have a style applied to an element using its ID, it's more specific than just using a class or tag.
  • Classes, attributes, and pseudo-classes: Styles applied using classes, attributes, or pseudo-classes are next in line. They're less specific than IDs but more specific than just tag names.
  • Element (tag) selectors: These are styles applied to all elements of a particular type. They're the least specific because they apply to all elements of that type.

What is the difference between 'class' and 'id' selectors in CSS?

Some key difference between 'class' and 'id' selectors:

Feature Class Selector ID Selector
Syntax Prefixed with a period (.) Prefixed with a hash (#)
Applicability Can be applied to multiple elements Unique to a single element
Specificity Less specific More specific
Usage Used to style multiple elements Used to style a single element
Restrictions Can be reused across multiple elements Should be unique within a document
JavaScript Can be targeted using JavaScript by class name Can be targeted using JavaScript by ID

How can you apply CSS to HTML?

CSS can be applied using inline styles, internal stylesheets, and external stylesheets. Inline styles are applied directly to an HTML element via the 'style' attribute, internal styles are placed within a '<style>' tag in the '<head>' section, and external styles are linked through a '.css' file.

What is a pseudo-class in CSS?

A pseudo-class in CSS is a keyword added to a selector that specifies a special state of the selected element(s). Pseudo-classes are used to style elements based on user interaction, such as when an element is hovered over or clicked, or based on its position within the document tree.

Some common examples of pseudo-classes:

  • hover: Applies styles when the mouse cursor is hovering over the element.
  • active: Applies styles when the element is being activated, such as when it is clicked.
  • focus: Applies styles when the element has focus, such as when it is selected by tabbing through form elements.
  • first-child: Selects the first child element of its parent.
  • nth-child(n): Selects elements based on their position within their parent, according to a formula (e.g., nth-child(odd) selects every odd-numbered child).

What is a pseudo-element in CSS?

A pseudo-element in CSS is like adding an extra part to an element without actually modifying the HTML. It lets you style parts of an element that aren't directly in the HTML structure

What are CSS preprocessors?

CSS preprocessors are tools that make writing CSS easier and more powerful. They introduce new features like variables, nesting, and reusable styles (called mixins) that help organize and streamline your CSS code. They basically make it simpler to write and manage your stylesheets for websites and web applications. Popular examples include Sass, LESS, and Stylus.

What is the difference between 'margin' and 'padding'?

Some key difference between 'margin' and 'padding':

Feature Margin Padding
Definition Space outside the border of an element. Space inside the border of an element.
Effect Creates space around the element, separating it from other elements. Adds space between the content of the element and its border.
Applied to Applied to the outside edge of an element. Applied to the inside edge of an element.
Impact on size Margins do not increase the size of the element. Padding increases the size of the element.
Collapsing Margins can collapse with adjacent margins of other elements. Padding does not collapse.

How do you center an element horizontally using CSS?

To center a block element, we can use 'margin: 0 auto;':

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

To center an inline element, we can use 'text-align: center;' on its parent.

What is the difference between 'relative', 'absolute', 'fixed', and 'sticky' positioning?

Some key difference between 'class' and 'id' selectors:

Relative Positioned relative to its normal position in the document flow. Moves the element from its original position based on specified offsets (top, right, bottom, left) without affecting the layout of other elements.
Absolute Positioned relative to its nearest positioned ancestor. If no ancestor is positioned, it's positioned relative to the initial containing block (usually the viewport). Removed from the normal document flow and positioned based on specified offsets (top, right, bottom, left). It doesn't affect the layout of other elements, and other elements act as if it doesn't exist.
Fixed Positioned relative to the viewport (browser window). Removed from the normal document flow and remains fixed in its position even when the page is scrolled. It's positioned based on specified offsets (top, right, bottom, left) relative to the viewport.
Sticky Initially positioned like 'relative' and becomes 'fixed' when a specified scroll position is reached. Acts like 'relative' positioning until the element reaches a specified scroll position (defined by 'top', 'right', 'bottom', or 'left' offsets), after which it becomes 'fixed' and remains in that position even when scrolling. Once the scrolling goes beyond the specified point, it returns to its original position in the document flow.

What are media queries?

Media queries are like instructions for your website to change its appearance based on the device someone is using. They help make sure your website looks good on all kinds of screens, from small phones to big desktop monitors. By using media queries, you can adjust things like font sizes, layout, and colors to fit different screen sizes and orientations.

How do you create a responsive layout in CSS?

Responsive layouts can be created using:

  • Media Queries: Define different styles for different screen sizes using @media queries. Adjust layout, font sizes, and other properties based on screen width.
  • Flexible Units: Use relative units like percentages (%) and viewport units (vw, vh) instead of fixed pixels. This allows elements to adapt to different screen sizes.
  • Fluid Grids: Design layouts using a grid system that scales with the viewport. Use CSS Grid or Flexbox to create flexible and responsive layouts.
  • Viewport Meta Tag: Include the <meta name="viewport" content="width=device-width, initial-scale=1.0"> meta tag in your HTML to ensure proper scaling on mobile devices.
  • Images and Media: Use max-width: 100%; on images and media elements to prevent them from overflowing their containers and maintain responsiveness.
  • Progressive Enhancement: Start with a simple layout for smaller screens and enhance it with additional styles and features for larger screens, ensuring a good user experience across all devices.

What is Flexbox?

Flexbox is a CSS layout module that provides an easy and efficient way to align and distribute space among items in a container. It includes properties like 'flex-direction', 'justify-content', 'align-items', and 'flex-wrap'.

What is CSS Grid Layout?

CSS Grid Layout is a powerful layout system in CSS that allows you to create two-dimensional grid-based layouts with rows and columns. It provides a flexible and intuitive way to structure and arrange elements on a web page, offering precise control over both the placement and alignment of content.

Key features of CSS Grid Layout include:

  • Grid Container and Grid Items: The grid container is the parent element that holds grid items. Grid items are the children of the grid container and are placed within the grid cells.
  • Rows and Columns: You can define rows and columns within the grid using the 'grid-template-rows' and 'grid-template-columns' properties, specifying their size, distribution, and alignment.
  • Grid Lines and Gutters: Grid lines are the horizontal and vertical lines that define the boundaries of the grid cells. Gutters are the spaces between grid cells.
  • Grid Tracks: Grid tracks are the spaces between grid lines, defining the size of rows and columns. You can specify the size of tracks using fixed lengths, percentages, or flexible units like 'fr' (fraction of available space) and 'auto' (automatically sized).
  • Grid Placement: You can place grid items anywhere within the grid using the 'grid-row' and 'grid-column' properties or the shorthand 'grid-area'. This allows for precise control over the layout of elements.
  • Responsive Design: CSS Grid Layout is well-suited for responsive design, allowing you to easily create layouts that adapt to different screen sizes and devices using media queries and flexible units.

How can you hide an element using CSS?

To hide an element using CSS, we can use one of these methods:

  • visibility: hidden;: Hides the element while still taking up space in the layout.
  • display: none;: Completely removes the element from the layout, including its space.
  • opacity: 0;: Makes the element transparent, effectively hiding it, but it still occupies space in the layout.
  • height: 0; width: 0;: Sets the height and width of the element to zero, effectively hiding it, but it still occupies space in the layout.

What are CSS animations?

CSS animations are a way to add movement and visual effects to HTML elements using CSS properties. They are defined using keyframes and controlled using animation properties. CSS animations offer a lightweight and efficient alternative to JavaScript-based animations, providing smooth and hardware-accelerated effects in modern web browsers.

What is the 'z-index' property?

The 'z-index' property in CSS controls the stacking order of elements on a web page along the z-axis (perpendicular to the screen). It determines which elements appear in front of or behind others when they overlap.

Some key points of 'z-index':

  • Stacking Context: The 'z-index' property works within a stacking context, which is created by any element with a position value other than static (e.g., relative, absolute, fixed, or sticky).
  • Values: The 'z-index' property accepts integer values, with higher values placing elements in front of those with lower values. It can also be negative, placing elements behind those with positive or zero values.
  • Parent-Child Relationship: Child elements are stacked relative to their parent’s stacking context. If two elements have the same 'z-index' value, the one defined later in the HTML code will appear on top.
  • Default Behavior: Elements with the same stacking context and no 'z-index' specified will stack in the order they appear in the document flow.

Explain the 'float' property in CSS.

The 'float' property in CSS is used to position elements horizontally within their containing element. When an element is floated, it is taken out of the normal document flow and positioned to the left or right within its containing element.

Some key points of 'float' property:

  • Values: It accepts two main values: 'left' and 'right'. When set to 'left', the element will float to the left, and content will flow around it on the right side. When set to 'right', the element will float to the right, and content will flow around it on the left side.
  • Clearing: When an element is floated, it may affect the layout of subsequent elements. You can use the 'clear' property to prevent this by specifying which side of the floated elements should not be touched by other floating elements.
  • Parent Element: When an element is floated, its containing element may collapse if it contains only floated elements. To prevent this, you can use the 'clearfix' technique or apply a clearfix class to the parent element.
  • Compatibility: While 'float' was commonly used for layout in the past, modern layout techniques like Flexbox and CSS Grid Layout are now preferred for creating complex layouts, as they offer more control and flexibility.

What is the purpose of the 'clear' property?

The 'clear' property in CSS is used to control the behaviour of elements that come after floated elements within the same container. When an element is cleared, it ensures that it appears below any preceding floated elements, preventing content from wrapping around floated elements. This property is often used to fix layout issues caused by floated elements, ensuring that subsequent content is displayed as intended without being affected by floating elements.

What are CSS transitions?

CSS transitions are a way to add smooth animations to CSS properties like color, size, and position changes. They are defined using the `transition` property and allow for gradual transitions between different property values over a specified duration. This provides a more engaging user experience by adding subtle animations to elements on a webpage.

What is the difference between 'inline' and 'block' elements?

Some key difference between 'inline' and 'block' elements:

Feature Inline Elements Block Elements
Definition Inline elements flow within the text of a document, side by side, without starting a new line. Block elements create a block-level box that starts on a new line and stretches to fill the width of its container.
Display Behavior Occupies only as much width as necessary and does not force a new line. Starts on a new line and takes up the full available width by default, pushing subsequent elements to a new line.
Dimensions Width and height do not apply. Width and height can be specified and adjusted.
Default Behavior Ignores top and bottom margin, padding, and width. Respects top and bottom margin, padding, and width.
Allowed Children Cannot contain block-level elements. Can contain both inline and block-level elements.
Default Styles Often used for small text elements or parts of text, like spans and links. Typically used for larger structural elements, like divs and paragraphs.

What is the purpose of the 'overflow' property?

The 'overflow' property controls how content that is too large for an element’s box is handled. Values include 'visible', 'hidden', 'scroll', and 'auto'.

What are CSS variables?

CSS variables, also known as custom properties, allow you to store values that can be reused throughout a document. They are defined using the '--' prefix and accessed using the 'var()' function.

:root {
  --main-color: #06c;
}
.element {
  color: var(--main-color);
}

How do you create a CSS triangle?

CSS triangles can be created using borders:

.triangle {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}

What is the 'calc()' function in CSS?

The 'calc()' function allows you to perform calculations to determine CSS property values. For example:

.element {
  width: calc(100% - 50px);
}

How can you use CSS to make an image circular?

You can make an image circular by setting its 'border-radius' to 50%:

.circular-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

What is a CSS 'reset' and why is it useful?

A CSS reset removes default browser styles to ensure consistency across different browsers. It is useful because different browsers have different default styles which can cause inconsistencies.

What is a CSS 'normalize'?

CSS Normalize is a CSS file that makes sure all browsers show elements like headings, paragraphs, and lists in a consistent way, fixing any differences between browsers. It doesn't remove all default styles like a reset does, but it smooths out the differences, making it easier to create websites that look the same across different browsers.

What is the difference between 'em' and 'rem' units?

Some key difference between 'em' and 'rem' units:

Feature 'em' Unit 'rem' Unit
Definition Relative to the font size of its parent element. Relative to the font size of the root element (html).
Cascading Inherits the font size from its parent element. Does not inherit font size and remains constant relative to the root element's font size.
Usage Useful for creating relative sizes within a component or section of a page. Preferred for defining global typographic scales and maintaining consistent spacing across the entire page.
Scaling Behavior Can compound if used within nested elements, causing the font size to multiply. Maintains a consistent size regardless of nesting, providing a more predictable and scalable layout.
Browser Support Supported in all modern browsers. Supported in all modern browsers.

What is the 'content' property in CSS?

The 'content' property is used with pseudo-elements like '::before' and '::after' to insert content:

.element::before {
  content: "Prefix";
}

How can you achieve text truncation with ellipsis in CSS?

We can use the following properties to truncate text with ellipsis:

.truncated {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

What is the purpose of the 'box-sizing' property?

The 'box-sizing' property defines how the total width and height of an element are calculated. Values include 'content-box' (default) and 'border-box'. 'border-box' includes padding and border in the element's total width and height.

How do you style visited links in CSS?

A CSS 'normalize' is a stylesheet that standardizes default styles across different web browsers, ensuring consistent appearance of HTML elements. Unlike resets, it targets only specific styling differences, reducing the need for browser-specific fixes in CSS.

a:visited {
  color: purple;
}

What is the purpose of the 'outline' property in CSS?

The 'outline' property in CSS is used to add a visible outline around an element, typically for accessibility or focus indication purposes. It is similar to the 'border' property but does not affect the layout of the element. The 'outline' is often used to highlight elements when they receive focus, such as links or form elements, making them more accessible to users navigating with keyboards or assistive technologies.

How do you create a gradient background in CSS?

Gradients can be created using the 'linear-gradient' or 'radial-gradient' functions:

.gradient-background {
  background: linear-gradient(to right, red, yellow);
}

What is the difference between 'nth-child' and 'nth-of-type' selectors?

Some key difference between 'nth-child' and 'nth-of-type' selectors:

Feature 'nth-child' Selector 'nth-of-type' Selector
Target Elements Selects elements based on their position relative to their parent, regardless of their type. Selects elements of a specific type based on their position relative to their parent.
Syntax Uses an expression inside parentheses, e.g., :nth-child(n) Uses an expression inside parentheses, e.g., :nth-of-type(n)
Targeted Elements Can select any type of element, regardless of its tag name. Selects elements of a specific type, such as divs, paragraphs, lists, etc.
Behavior Applies the style based on the element's position in the parent, regardless of its type. Applies the style based on the element's position within its type-specific siblings.
Usage Useful when targeting elements without considering their type, like alternating rows in a table. Useful when styling elements of a specific type within a container, like alternating paragraphs.

What is a CSS 'sprite'?

A CSS sprite is a single image file that contains multiple images. By using CSS, you can display different parts of the sprite image as needed, reducing the number of HTTP requests and improving performance.

How can you create a responsive navbar using CSS?

A responsive navbar can be created using flexbox or grid layout, along with media queries to adjust the layout for different screen sizes.

What is the 'clamp()' function in CSS?

The 'clamp()' function allows you to set a value within a range. It takes three parameters: a minimum value, a preferred value, and a maximum value:

.element {
  font-size: clamp(1rem, 2vw, 2rem);
}

How do you make a div fill the remaining height of the viewport?

You can use flexbox to make a div fill the remaining height of the viewport:

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.content {
  flex: 1;
}

What are CSS counters?

CSS counters are variables that can be incremented by CSS rules to track how many times they are used. They are often used for creating ordered lists and custom counters.

How can you prevent text from wrapping in CSS?

To prevent text from wrapping, you can use the 'white-space' property with the 'nowrap' value:

.nowrap {
  white-space: nowrap;
}

What is the difference between 'visibility: hidden' and 'display: none'?

Some key difference between 'visibility: hidden' and 'display: none':

Feature 'visibility: hidden' 'display: none'
Visibility Element is hidden but still occupies space in the layout. Element is removed from the layout and does not occupy any space.
Accessible Content remains accessible to screen readers and assistive technologies. Content is not accessible to screen readers or assistive technologies.
Effect on Layout Leaves a space where the element would be, affecting layout flow. Does not leave any space and does not affect layout flow.
Event Handling Element still triggers events and can be interacted with via JavaScript. The element does not trigger events and cannot be interacted with via JavaScript.
Rendering Renders the element's box, but makes it invisible. Completely removes the element from rendering.
Performance May impact performance if many elements are hidden, as they still need to be rendered. Better performance as elements are not rendered at all.

What are the different ways to apply colours in CSS?

Colours can be applied using colour names (e.g., 'red'), hexadecimal values (e.g., '#ff0000'), RGB values (e.g., 'rgb(255, 0, 0)'), RGBA values (e.g., 'rgba(255, 0, 0, 0.5)'), HSL values (e.g., 'hsl(0, 100%, 50%)'), and HSLA values (e.g., 'hsla(0, 100%, 50%, 0.5)').

How can you create a CSS tooltip?

CSS tooltips can be created using the 'title' attribute along with some styling for the tooltip container:

.tooltip {
  position: relative;
  display: inline-block;
}
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 5px;
  padding: 5px;
  position: absolute;
  z-index: 1;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;
}
.tooltip:hover .tooltiptext {
  visibility: visible;
}

What is the 'display: flex;' property used for?

The 'display: flex;' property is used to create a flex container, which allows you to use flexbox properties to align and distribute space among the container's items.

How do you create a fixed header or footer using CSS?

A fixed header or footer can be created using the 'position: fixed;' property:

.header {
  position: fixed;
  top: 0;
  width: 100%;
}
.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
}

What is the 'backdrop-filter' property in CSS?

The 'backdrop-filter' property applies graphical effects such as blurring or color shifting to the area behind an element:

.blur-background {
  backdrop-filter: blur(10px);
}

How can you create a responsive image gallery using CSS?

To create a responsive image gallery using CSS, you can follow these steps:

  • HTML Structure: Start by structuring your HTML to represent the image gallery. Use appropriate HTML elements such as <div>, <figure>, and <img> to organize your images.
  • CSS Styling: Apply CSS styles to make the gallery responsive. Use percentage-based widths to ensure that images adjust fluidly to different screen sizes. Use CSS Flexbox or CSS Grid Layout to create a flexible and responsive layout for the gallery container and its items.
  • Media Queries: Use media queries to adjust the gallery layout and styling for different screen sizes. Define breakpoints where the gallery layout needs to change to accommodate smaller or larger screens. Adjust margins, padding, or column layouts to optimize the gallery display on different devices.
  • Image Scaling: Use the 'object-fit' property in CSS to control how images are scaled and fitted within their containers. This ensures that images maintain their aspect ratio and display correctly across various screen sizes.

What is the 'object-fit' property used for in CSS?

The 'object-fit' property specifies how the content of a replaced element (e.g., '<img>', '<video>') should be resized to fit its container. Values include 'fill', 'contain', 'cover', 'none', and 'scale-down'.

How can you create a CSS-only modal?

A CSS-only modal can be created using the ':target' pseudo-class:

.modal {
  display: none;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#modal:target {
  display: block;
}

What is the 'cursor' property in CSS?

The 'cursor' property in CSS is used to specify the type of cursor to be displayed when the mouse pointer is over an element. It allows you to customize the appearance of the cursor to provide visual feedback to users based on the interaction context.

Using 'cursor' property, we can set various cursor styles, such as:

  • Pointer: The cursor is a pointing hand, indicating that the element is clickable.
  • Default: The default cursor for the browser or operating system.
  • Crosshair: The cursor is a crosshair, indicating selection or drawing mode.
  • Text: The cursor is a vertical text caret, indicating text input mode.
  • Help: The cursor is a question mark, indicating help or information.
  • Progress: The cursor is a spinning wheel or hourglass, indicating that the browser is busy.

How do you apply styles for printing in CSS?

Styles for printing can be applied using a media query for the 'print' media type:

@media print {
  body {
    font-size: 12pt;
  }
  .no-print {
    display: none;
  }
}

What is the 'all' property in CSS?

The 'all' property resets all properties, except 'unicode-bidi' and 'direction', to their initial or inherited values:

.reset-all {
  all: unset;
}

How do you create a drop shadow using CSS?

A drop shadow can be created using the 'box-shadow' property:

.shadow {
  box-shadow: 10px 10px 5px #888888;
}

What is the 'isolation' property in CSS?

The 'isolation' property determines whether an element's blend mode is isolated from its parent:

.isolated {
  isolation: isolate;
}

How can you create a multi-column layout using CSS? 

A multi-column layout can be created using the 'column-count' or 'column-width' properties:

.multi-column {
  column-count: 3;
  column-gap: 20px;
}