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.
The box model represents the structure of a web page element. This model allows us to create design and layout for HTML elements.
Specificity determines which CSS rule is applied by the browser when multiple rules match the same element. It follows this order:
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 |
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.
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:
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
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.
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. |
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.
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. |
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.
Responsive layouts can be created using:
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'.
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:
To hide an element using CSS, we can use one of these methods:
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.
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':
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:
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.
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.
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. |
The 'overflow' property controls how content that is too large for an element’s box is handled. Values include 'visible', 'hidden', 'scroll', and 'auto'.
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);
}
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;
}
The 'calc()' function allows you to perform calculations to determine CSS property values. For example:
.element {
width: calc(100% - 50px);
}
You can make an image circular by setting its 'border-radius' to 50%:
.circular-image {
width: 100px;
height: 100px;
border-radius: 50%;
}
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.
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.
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. |
The 'content' property is used with pseudo-elements like '::before' and '::after' to insert content:
.element::before {
content: "Prefix";
}
We can use the following properties to truncate text with ellipsis:
.truncated {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
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.
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;
}
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.
Gradients can be created using the 'linear-gradient' or 'radial-gradient' functions:
.gradient-background {
background: linear-gradient(to right, red, yellow);
}
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. |
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.
A responsive navbar can be created using flexbox or grid layout, along with media queries to adjust the layout for different screen sizes.
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);
}
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;
}
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.
To prevent text from wrapping, you can use the 'white-space' property with the 'nowrap' value:
.nowrap {
white-space: nowrap;
}
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. |
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)').
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;
}
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.
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%;
}
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);
}
To create a responsive image gallery using CSS, you can follow these steps:
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'.
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;
}
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:
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;
}
}
The 'all' property resets all properties, except 'unicode-bidi' and 'direction', to their initial or inherited values:
.reset-all {
all: unset;
}
A drop shadow can be created using the 'box-shadow' property:
.shadow {
box-shadow: 10px 10px 5px #888888;
}
The 'isolation' property determines whether an element's blend mode is isolated from its parent:
.isolated {
isolation: isolate;
}
A multi-column layout can be created using the 'column-count' or 'column-width' properties:
.multi-column {
column-count: 3;
column-gap: 20px;
}