1. How can you optimize CSS animations for performance?
Animate only opacity and transform when possible. Use `will-change` hints, avoid heavy shadows or large repaints, and prefer GPU-accelerated properties.
div { will-change: transform, opacity; }Get the Preplance app for a seamless learning experience. Practice offline, get daily streaks, and stay ahead with real-time interview updates.
Get it on
Google Play
4.9/5 Rating on Store
Cognizant · CSS
Practice CSS questions specifically asked in Cognizant interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
90
Tagged for this company + subject
Company
Cognizant
View company-wise questions
Subject
CSS
Explore topic-wise practice
Go through each question and its explanation. Use this page for targeted revision just before your Cognizant CSS round.
Animate only opacity and transform when possible. Use `will-change` hints, avoid heavy shadows or large repaints, and prefer GPU-accelerated properties.
div { will-change: transform, opacity; }For complete preparation, combine this company + subject page with full company-wise practice and subject-wise practice. You can also explore other companies and topics from the links below.
Combinators define relationships between selectors. The main ones are: space (descendant), '>' (child), '+' (adjacent sibling), and '~' (general sibling). They help target elements precisely based on their structural relation.
.parent > .child, h2 + p, h2 ~ ul
The selector p.intro means: select all <p> elements that have the class 'intro'. This is basic CSS selector syntax — very common in interviews.
p.intro { color: blue; }`animation-fill-mode` defines how an element looks before or after animation. Using `forwards` keeps the last keyframe state, useful for effects like slide-in that should stay visible.
div { animation: fadeIn 1s forwards; }Frequent mistakes include using too many breakpoints, defining overlapping rules, using `max-width` inconsistently, not testing portrait vs landscape, and ignoring the viewport meta tag.
Avoid: @media (max-width: 768px) and (min-width: 800px) { ... }Declaring variables inside `:root` makes them global, similar to defining them at the document level. Variables declared in other selectors are local to that scope.
:root { --font-size: 16px; }`calc()` lets you combine different units dynamically (%, px, rem) — for example: `width: calc(100% - 50px);`. Useful for fluid layouts and spacing adjustments.
section { width: calc(100% - 40px); }`clamp(min, preferred, max)` allows fluid, responsive values while preventing them from exceeding given limits — ideal for responsive font sizes.
h1 { font-size: clamp(1rem, 4vw, 2rem); }The `rgba()` function defines colors with alpha transparency. Example: `rgba(255, 0, 0, 0.5)` creates a semi-transparent red background.
div { background-color: rgba(0, 0, 255, 0.2); }The `filter` property applies graphical effects like blur, brightness, contrast, or grayscale directly in CSS without modifying the source image.
img { filter: grayscale(100%); }The `mix-blend-mode` property determines how element colors blend with background content, allowing creative effects like multiply, overlay, and screen.
img { mix-blend-mode: multiply; }CSS variables store reusable values, making design updates easier. For example, changing `--primary-color` in one place updates it across the project. They also enable light/dark themes dynamically via JavaScript or user preferences.
:root { --primary-color: #2196f3; } body { color: var(--primary-color); }You can provide fallback values inside `var()`. For example, `color: var(--text-color, black);` ensures `black` is used if the variable isn’t set — preventing rendering issues.
p { color: var(--accent, #000); }Yes, filters like blur or brightness are GPU-intensive. Overusing them can slow rendering, especially on low-end devices. Use them sparingly and prefer optimized images when possible.
img:hover { filter: brightness(1.2); }`transition-property` defines which CSS property changes should animate. Restricting it improves performance.
div { transition-property: background-color; transition-duration: 0.5s; }`ease-in-out` accelerates midway then decelerates, creating smooth natural motion. It’s commonly used for hover or modal transitions.
a:hover { transition: all 0.3s ease-in-out; }`animation-iteration-count` controls how many times an animation repeats. Setting it to `infinite` loops it endlessly.
div { animation: pulse 2s infinite; }`transform` applies 2D/3D transformations like `rotate()`, `scale()`, and `translate()`. It’s GPU-optimized and commonly animated.
div:hover { transform: scale(1.1) rotate(5deg); }`opacity` and `transform` are GPU-accelerated and don’t trigger layout or repaint, making them ideal for smooth animations.
div:hover { opacity: 0.8; transform: scale(1.05); }Use keyframes for multi-step animations like loading spinners or looping effects. Transitions are best for simple hover or focus changes.
@keyframes bounce { 0%,100% { top:0; } 50% { top:-20px; } }Float is used to move elements like images or boxes to the left or right so that text wraps around them. The clear property is used to stop elements from wrapping around floated items. For example, after floating an image right, applying clear: both to the next section ensures it starts below.
img { float: right; }
.footer { clear: both; }Easing defines acceleration over time — `linear` is constant, `ease-in` starts slow, `ease-out` ends slow, `ease-in-out` smooths both ends. It adds realism and polish to motion.
button:hover { transition: all 0.3s ease-in-out; }Selectors target elements for styling. They help apply consistent design to multiple elements without duplication. Good selector use means cleaner, maintainable code — a skill companies value in interviews.
button.primary { background-color: green; }CSS combinators define relationships between selectors. A space indicates descendant, '>' means direct child, '+' selects the next sibling, and '~' selects all following siblings. These help in selecting elements based on their hierarchy in HTML.
div + p { color: red; }`transition` shorthand includes property, duration, timing-function, and delay. `iteration-count` belongs to animations, not transitions.
div { transition: all 0.5s ease-in-out; }Mobile-first means designing and coding for smaller screens first, then progressively enhancing for larger screens using min-width media queries. This ensures performance, better UX, and scalability.
@media (min-width: 768px) { .grid { grid-template-columns: 1fr 1fr; } }An ID selector has higher specificity than class or element selectors. The priority order in CSS is inline styles, then IDs, then classes, then elements.
#box { color: red; } /* overrides */
.box { color: blue; }`vh` and `vw` scale elements according to the viewport size, making designs automatically adjust to different screen sizes without needing breakpoints. For example, hero sections often use height: 100vh.
header { height: 100vh; background-size: cover; }Use `max-width: 100%` and `height: auto` to resize images fluidly. Combine with `srcset` or `<picture>` for device-specific resolutions to reduce load time on smaller devices.
<img srcset='small.jpg 600w, large.jpg 1200w' src='large.jpg' alt='example'>
CSS stands for Cascading Style Sheets. It is used to style HTML elements — controlling layout, colors, and fonts. In interviews, explaining that CSS separates design from content shows understanding of modern web practices.
body { background-color: lightblue; }The correct syntax is p { color: red; }. The property 'color' changes the text color. This tests basic CSS property knowledge — often asked in coding rounds.
p { color: red; }A class selector begins with a dot. The selector '.intro' selects all elements that have class='intro'. Classes are reusable for multiple elements.
.intro { font-size: 18px; }The selector 'div span' selects every span element that is nested anywhere inside a div, regardless of the depth. It helps style inner elements within containers.
div span { color: red; }CSS has five main position values: static, relative, absolute, fixed, and sticky. Static is default and doesn’t move. Relative moves an element based on its normal position. Absolute positions relative to the nearest positioned ancestor. Fixed stays in place during scroll. Sticky combines relative and fixed behaviors depending on scroll offset.
div { position: absolute; top: 0; }z-index defines how elements overlap along the z-axis. It works only on positioned elements. Each positioned element can create a new stacking context, meaning its children are stacked independently from the rest of the page. Higher z-index values appear above lower ones within the same context.
.popup { position: relative; z-index: 10; }You can fix it by setting a higher z-index and ensuring the tooltip’s parent has a proper stacking context. Often the issue arises because a parent element has a lower z-index or overflow set to hidden, preventing proper layering.
.tooltip { position: absolute; z-index: 9999; }The `fr` (fraction) unit distributes remaining space among grid tracks proportionally. For example, `1fr 2fr` divides free space in 1:2 ratio.
.grid { grid-template-columns: 1fr 2fr; }CSS specificity decides which rule will be applied when multiple rules target the same element. Inline styles have the highest priority, followed by ID selectors, class selectors, and element selectors. Understanding specificity is important to control style conflicts and maintain consistent design.
#id > .class > p
When CSS rules conflict, you can open the browser’s Developer Tools and inspect the element. The 'Computed' tab shows the final applied styles. The browser uses specificity and the cascade order to determine which rule wins.
/* Use browser DevTools > Computed Styles */
The box model starts with the content area, followed by padding, border, and then margin on the outermost layer. This determines how space is distributed around elements.
/* Inside to outside */ Content → Padding → Border → Margin
Inline elements cannot have width or height applied directly. To control their size, you can change their display type to inline-block or block.
span { display: inline-block; width:100px; }An inline-block element behaves like inline content but supports block properties such as width, height, and vertical margins, making it ideal for layouts like navigation menus.
span { display: inline-block; width:80px; }The box-sizing property controls how the total size of an element is calculated. In content-box, padding and border are added to width and height. In border-box, padding and border are included inside the total width and height. border-box makes layout management easier and is widely used in modern CSS resets.
* { box-sizing: border-box; }display: none completely removes the element from the layout, as if it doesn’t exist, while visibility: hidden hides the element but keeps its original space reserved. This is useful for animations, toggles, and accessibility control in UI design.
.box { visibility:hidden; }To fix overflowing, check padding, border, or box-sizing. Apply box-sizing: border-box to include borders inside total width or use overflow: hidden to clip excess content. Understanding the box model helps solve layout issues quickly.
.container { overflow:hidden; box-sizing:border-box; }A sticky element toggles between relative and fixed positioning depending on the scroll position. It stays fixed only after crossing a defined offset.
header { position: sticky; top: 0; }The float property moves an element to the left or right, allowing inline content like text or images to wrap around it. It was commonly used for layouts before Flexbox and Grid.
img { float: right; margin: 10px; }z-index determines the stacking order of positioned elements. Elements with a higher z-index appear above those with a lower value, but it works only on elements with a position other than static.
.modal { position: absolute; z-index: 999; }When you mark an element as `display: flex`, its **direct children** become flex items. Nested deeper descendants do not automatically become flex items unless their parent is also a flex container. :contentReference[oaicite:2]{index=2}
<div class="container" style="display:flex;"> <div>A</div> <div>B</div> </div>
Valid values for `flex-direction` include `row`, `row-reverse`, `column`, and `column-reverse`. `baseline` is not a valid direction. `baseline` is used in alignment contexts (like align-items) but not for direction. :contentReference[oaicite:4]{index=4}
.container { flex-direction: column-reverse; }Using `flex-wrap: wrap` on a flex container permits items to wrap onto next lines if they overflow the container width. The default is `nowrap`. :contentReference[oaicite:6]{index=6}
.container { display:flex; flex-wrap: wrap; }`display: flex` makes the element a block-level flex container (takes full width, new line). `inline-flex` makes the container inline (flows within text) while still applying flex behavior to its children. So inline-flex does not break the line. :contentReference[oaicite:9]{index=9}
.menu { display: inline-flex; }The `order` property determines the visual order of a flex item relative to its siblings. Items with lower order values appear first. You can change layout order without altering HTML. The default `order` is 0. Negative or positive values shift placement. Example: `.item { order: -1; }` moves it to the front. :contentReference[oaicite:10]{index=10}
.item-1 { order: 2; } .item-2 { order: 1; }When an element is set as a grid container, all its **direct children** become grid items that can be positioned within rows and columns defined by grid properties.
.grid { display: grid; }`gap` (formerly grid-gap) defines the spacing between rows and columns inside the grid, without affecting the content of grid items.
.grid { gap: 20px; }Grid lines are numbered starting from 1 at the top-left corner horizontally and vertically. You can place items using these line numbers.
.item { grid-column: 1 / 3; }`minmax(200px, 1fr)` sets each column to be at least 200 pixels wide but flexible up to available free space. Combined with `auto-fit`, it creates fully responsive grids that adapt to viewport width.
.grid { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }An explicit grid is defined by properties like `grid-template-rows` and `grid-template-columns`. Any item outside this defined structure goes into the implicit grid, automatically created by the browser to hold overflow items. You can control their sizing using `grid-auto-rows` or `grid-auto-columns`.
.grid { grid-template-columns: 200px 1fr; grid-auto-rows: 100px; }The `perspective` property defines the distance between the viewer and the 3D element, allowing elements to appear with depth. Used alongside transform-style: preserve-3d.
.scene { perspective: 600px; }`animation-iteration-count` defines how many times an animation should repeat. You can use numbers or `infinite` for continuous looping.
.box { animation-iteration-count: infinite; }Easing functions like `ease-in`, `ease-out`, and `cubic-bezier()` define acceleration and deceleration of animations for natural motion. They make movement look more realistic rather than linear, improving UX and feel of transitions.
.box { transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1); }`transform-origin` defines the point around which transforms like rotation or scaling occur. For example, `transform-origin: left top;` rotates around the top-left instead of the default center point.
.icon { transform-origin: left top; transform: rotate(45deg); }Viewport height (vh) and viewport width (vw) are relative to the visible screen size. `1vh` = 1% of viewport height; `1vw` = 1% of viewport width.
section { height: 100vh; width: 100vw; }An ID selector uses a hash (#). The rule '#header{}' styles the element with that specific ID. Each ID should be unique within a page.
#header { background-color: #333; }Specificity is calculated as ID > Class > Element. '#main p' includes an ID, giving it higher specificity than class or element selectors.
#main p { color: red; }`::before` is the correct modern syntax (double colon) for inserting generated content before an element. It requires `content:` property to work.
h1::before { content: '👉 '; color: orange; }Specificity determines which CSS rule wins when multiple rules target the same element. The hierarchy is: Inline styles (highest), IDs, Classes/Attributes/Pseudo-classes, and then Elements/Pseudo-elements. A rule with an ID selector overrides one with only classes or tags.
#id (100 points) > .class (10 points) > element (1 point)
The browser applies the rule with higher specificity. If equal, the later one in the CSS file wins. You can inspect elements in DevTools to see which rules are crossed out or overridden.
/* Example */ #title {color:red;} .heading {color:blue;} /* red wins */A relatively positioned element remains in the document flow but can be offset visually using top, left, bottom, or right properties.
div { position: relative; top: 10px; left: 20px; }A new stacking context forms when an element is positioned (other than static) and has a z-index. It isolates child z-index layers from the outer context.
.container { position: relative; z-index: 10; }Absolutely and fixed positioned elements are removed from normal document flow, meaning they do not affect the positioning of surrounding elements.
div { position: absolute; top: 50px; left: 50px; }Because z-index works only within the same stacking context. If a parent creates its own stacking context (e.g., via position and z-index), child elements can’t overlap elements outside that context, no matter their z-index.
.parent { position: relative; z-index: 1; } .child { z-index: 9999; }Apply `position: sticky` with `top: 0`. This allows the header to scroll with the page until it reaches the top, then it sticks. Ensure parent containers do not have overflow hidden, or it won’t work.
header { position: sticky; top: 0; background: white; z-index: 100; }Inspect with DevTools to check stacking context, z-index values, and position types. Simplify by removing z-indexes step-by-step. Remember z-index only works on positioned elements. Check parent overflow and isolation too.
div { position: relative; z-index: 5; }Mobile-first design starts with base mobile styles and adds rules for larger devices using `min-width`. This ensures smaller screens load faster with fewer overrides.
@media (min-width: 768px) { .container { width: 80%; } }The 768px breakpoint typically targets tablets in portrait orientation. Other standard breakpoints include 480px (mobile) and 1024px (desktop).
@media (max-width: 768px) { nav { display: none; } }The viewport meta tag ensures the browser sets proper scaling for mobile devices. Without it, pages appear zoomed out. Example: `<meta name='viewport' content='width=device-width, initial-scale=1.0'>`
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
`align-content` controls how multiple rows (or columns) of flex items are spaced along the cross axis **only when the items wrap** and there is leftover space. It has no effect in a single line layout. :contentReference[oaicite:7]{index=7}
.container { flex-wrap: wrap; align-content: space-between; }Position: relative keeps the element in the normal document flow but allows it to move relative to its original position using top, right, bottom, or left properties.
div { position: relative; top: 10px; }The 'border-box' value makes the browser include padding and border within the total width and height. This prevents layout shifts and is preferred in modern web design.
box-sizing: border-box;
CSS comments are written between /* and */. Comments are ignored by the browser and used to describe code sections — useful for teamwork and interviews about best practices.
/* This is a CSS comment */
p { color: blue; }The attribute selector input[type='text'] applies styles to input fields whose type is text. It’s useful for form-specific styling and improving UI consistency.
input[type='text'] { border: 1px solid gray; }Grid areas let you assign names to specific sections of a grid for easy placement. You define them in `grid-template-areas` and assign to items via `grid-area`. This makes large layouts more readable and maintainable.
.grid { grid-template-areas: 'header header' 'sidebar main'; } .header { grid-area: header; }`animation-fill-mode: forwards` ensures the element retains the final keyframe’s styles after the animation completes instead of reverting to its initial state.
.fadeIn { animation-fill-mode: forwards; }`@keyframes` define stages of an animation using percentages. Each stage sets different CSS properties. For example, a fade-in uses `from {opacity:0}` and `to {opacity:1}`. The animation plays over the defined duration and can loop or reverse based on configuration.
@keyframes fadeIn { from{opacity:0;} to{opacity:1;} } .box{ animation: fadeIn 2s ease; }A descendant selector selects all matching elements inside a parent, regardless of depth. '.card p' applies to all <p> within .card at any level.
.card p { color: gray; }Touch devices don’t have a traditional hover state. The first tap often triggers :hover but may not persist. Instead, use :active or JavaScript touch events for responsive feedback, or provide clear visual focus states.
button:active { background: #333; }An absolutely positioned element is taken out of the normal flow and positioned relative to its nearest ancestor with a position other than static. If none exists, it positions relative to the document body.
.child { position: absolute; top: 0; left: 0; }Sticky combines relative and fixed behavior. It scrolls with content until a defined position (like top: 0) and then sticks to that position.
header { position: sticky; top: 0; background: white; }Use `calc()` for dynamic arithmetic layouts, `min()` or `max()` for responsive limits. For instance, `width: min(90vw, 1200px)` restricts width to 1200px maximum while remaining fluid below that.
main { width: min(90vw, 1200px); }