• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? 10 Tricky CSS Questions for Frontend Developer Interviews (with Answers & Examples)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
CSS can feel simple—until it's not. In interviews for frontend roles, seasoned developers often face CSS questions that test deeper understanding of the cascade, specificity, layout behaviors, and browser quirks.

In this post, I’ve compiled 10 advanced and tricky CSS questions you're likely to encounter, along with detailed answers and examples.

1. ? Why doesn’t margin: auto center a div vertically?


Question:
You try to center a block-level element using:


.center {
margin: auto;
height: 100px;
}

Why doesn't this vertically center it inside its parent?

Answer:
margin: auto works for vertical centering only if:

  • The parent has a defined height
  • The child is not using position: static or position: relative
  • The child has a fixed height

But most importantly, vertical margin: auto doesn’t work in normal flow—you need flex or grid for that.

Fix:
Use flexbox:


.parent {
display: flex;
align-items: center;
justify-content: center;
}
2. ⚠ What’s the difference between em, rem, %, and vw/vh units?


Question:
How do em, rem, %, and vw/vh differ? Give a scenario where using em can cause unexpected layout issues.

Answer:

UnitRelative To
emCurrent element’s font size
remRoot (html) font size
%Parent’s dimension (font-size or box model, context-dependent)
vw/vhViewport width/height

Tricky case: Nested em values compound:


html { font-size: 16px; }

.card {
font-size: 1.2em; /* 19.2px */
}

.card .title {
font-size: 1.5em; /* 1.5 * 19.2 = 28.8px */
}

To avoid compounding, prefer rem.

3. ? Explain the stacking context. When does a new one form?


Answer:

A new stacking context is formed when an element has:

  • position: absolute | relative | fixed + z-index other than auto
  • opacity < 1
  • transform, filter, perspective, will-change
  • mix-blend-mode, isolation: isolate

Example:


.modal {
position: relative;
z-index: 10;
opacity: 0.99; /* forms new stacking context */
}

Trick: Even if a child has a higher z-index, it can’t escape its parent stacking context.

4. ? Why doesn’t overflow: hidden always work on flex containers?


Answer:

In a flex container, children with min-height: auto can overflow because of intrinsic sizing or scrolling content.

Also, if the child uses position: absolute, it is removed from flow, and overflow: hidden won’t affect it.

Fix: Ensure the child is not position: absolute, and remove min-height: auto if present.

5. ? What happens when you set display: contents?


Answer:

display: contents removes the element from the box tree but keeps its children in the DOM and style flow.

Example:


<div class="wrapper">
<div class="contents">Text <span>inside</span></div>
</div>

.contents {
display: contents;
}

The .contents element has no box—it’s transparent in layout. Its children behave as if they’re inside .wrapper.

Caveat: Accessibility tools (like screen readers) may ignore display: contents in some cases. Use cautiously.

6. ? Explain specificity. What’s the specificity of ul li a.button?


Answer:

CSS specificity is a 4-part score: (inline, IDs, classes, elements)

For ul li a.button:

  • No inline styles → 0
  • No IDs → 0
  • .button → 1 class → 0-0-1
  • ul, li, a → 3 elements → 0-0-1-3

Final score: 0-0-1-3

Compare with #nav a (1 ID, 1 element): 0-1-0-1, which wins.

7. ⚖ What’s the difference between visibility: hidden, opacity: 0, and display: none?


Answer:

PropertyVisible?Takes Space?Interactive?
visibility: hidden❌✅❌
opacity: 0❌✅✅ (still clickable)
display: none❌❌❌

Gotcha: opacity: 0 elements can still trigger events, which may lead to bugs.

8. ? How do you make a square responsive div?


Answer:

Use aspect ratio hacks:


.square {
width: 100%;
aspect-ratio: 1 / 1;
}

Old-school fallback:


.square {
width: 100%;
padding-top: 100%;
position: relative;
}
.square > * {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
9. ? Why doesn't position: sticky work?


Answer:
Common reasons:

  • The parent has overflow: hidden | auto | scroll
  • The element has no top/left/right/bottom specified
  • Not enough scrollable space for it to become "stuck"

Example:


.sticky {
position: sticky;
top: 0; /* required */
}

Tip: Use DevTools → Layers tab to debug.

10. ? What happens when you apply transition: all to display?


Answer:

Nothing.
display is not animatable. It changes instantly.

To animate entry/exit:


.fade {
opacity: 0;
visibility: hidden;
transition: opacity 0.3s;
}

.fade.show {
opacity: 1;
visibility: visible;
}

Use visibility + opacity + optional pointer-events, not display, for transitions.

? Final Thoughts


Mastering CSS isn’t about memorizing properties—it’s about deeply understanding how the browser thinks. These questions often trip up even experienced developers. So if you got stuck on a few, don’t worry. Dig deeper, test in the browser, and stay curious.

? What’s the trickiest CSS bug you’ve faced? Drop it in the comments!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу