CSS Interview Questions 2 Flashcards
Explain how a browser determines what elements match a CSS selector.
This part is related to the above about writing efficient CSS. Browsers match selectors from rightmost (key selector) to left. Browsers filter out elements in the DOM according to the key selector and traverse up its parent elements to determine matches. The shorter the length of the selector chain, the faster the browser can determine if that element matches the selector.
For example with this selector p span, browsers firstly find all the <span> elements and traverse up its parent all the way up to the root to find the <p> element. For a particular <span>, as soon as it finds a <p>, it knows that the <span> matches and can stop its matching.</span></span></span>
Describe pseudo-elements and discuss what they are used for.
A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). They can be used for decoration (:first-line, :first-letter) or adding elements to the markup (combined with content: …) without having to modify the markup (:before, :after).
:first-line and :first-letter can be used to decorate text.
Used in the .clearfix hack as shown above to add a zero-space element with clear: both.
Triangular arrows in tooltips use :before and :after. Encourages separation of concerns because the triangle is considered part of styling and not really the DOM.
Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model. Each box has a content area (e.g. text, an image, etc.) and optional surrounding padding, border, and margin areas.
The CSS box model is responsible for calculating:
How much space a block element takes up.
Whether or not borders and/or margins overlap, or collapse.
A box’s dimensions.
The box model has the following rules:
The dimensions of a block element are calculated by width, height, padding, borders, and margins.
If no height is specified, a block element will be as high as the content it contains, plus padding (unless there are floats, for which see below).
If no width is specified, a non-floated block element will expand to fit the width of its parent minus padding.
The height of an element is calculated by the content’s height.
The width of an element is calculated by the content’s width.
By default, paddings and borders are not part of the width and height of an element.
What does * { box-sizing: border-box; } do? What are its advantages?
By default, elements have box-sizing: content-box applied, and only the content size is being accounted for.
box-sizing: border-box changes how the width and height of elements are being calculated, border and padding are also being included in the calculation.
The height of an element is now calculated by the content’s height + vertical padding + vertical border width.
The width of an element is now calculated by the content’s width + horizontal padding + horizontal border width.
Taking into account paddings and borders as part of our box model resonates better with how designers actually imagine content in grids.
What is the CSS display property and can you give a few examples of its use?
display Description
none Does not display an element (the element no longer affects the layout of the document). All child element are also no longer displayed. The document is rendered as if the element did not exist in the document tree
block The element consumes the whole line in the block direction (which is usually horizontal)
inline Elements can be laid out beside each other
inline-block Similar to inline, but allows some block properties like setting width and height
table Behaves like the <table> element
table-row Behaves like the <tr> element
table-cell Behaves like the <td> element
list-item Behaves like a <li> element which allows it to define list-style-type and list-style-position
What’s the difference between inline and inline-block?
I shall throw in a comparison with block for good measure.
block inline-block inline Size Fills up the width of its parent container. Depends on content. Depends on content. Positioning Start on a new line and tolerates no HTML elements next to it (except when you add float) Flows along with other content and allows other elements beside it. Flows along with other content and allows other elements beside it. Can specify width and height Yes Yes No. Will ignore if being set. Can be aligned with vertical-align No Yes Yes
What’s the difference between a relative, fixed, absolute and statically positioned element?
A positioned element is an element whose computed position property is either relative, absolute, fixed or sticky.
static - The default position; the element will flow into the page as it normally would. The top, right, bottom, left and z-index properties do not apply.
relative - The element’s position is adjusted relative to itself, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).
absolute - The element is removed from the flow of the page and positioned at a specified position relative to its closest positioned ancestor if any, or otherwise relative to the initial containing block. Absolutely positioned boxes can have margins, and they do not collapse with any other margins. These elements do not affect the position of other elements.
fixed - The element is removed from the flow of the page and positioned at a specified position relative to the viewport and doesn’t move when scrolled.
sticky - Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
What existing CSS frameworks have you used locally, or in production? How would you change/improve them?
Bootstrap - Slow release cycle. Bootstrap 4 has been in alpha for almost 2 years. Add a spinner button component, as it is widely used.
Semantic UI - Source code structure makes theme customization extremely hard to understand. Its unconventional theming system is a pain to customize. Hardcoded config path within the vendor library. Not well-designed for overriding variables unlike in Bootstrap.
Bulma - A lot of non-semantic and superfluous classes and markup required. Not backward compatible. Upgrading versions breaks the app in subtle manners.
Have you played around with the new CSS Flexbox or Grid specs?
Yes. Flexbox is mainly meant for 1-dimensional layouts while Grid is meant for 2-dimensional layouts.
Flexbox solves many common problems in CSS, such as vertical centering of elements within a container, sticky footer, etc. Bootstrap and Bulma are based on Flexbox, and it is probably the recommended way to create layouts these days. Have tried Flexbox before but ran into some browser incompatibility issues (Safari) in using flex-grow, and I had to rewrite my code using inline-blocks and math to calculate the widths in percentages, it wasn’t a nice experience.
Grid is by far the most intuitive approach for creating grid-based layouts (it better be!) but browser support is not wide at the moment.
Can you explain the difference between coding a website to be responsive versus using a mobile-first strategy?
Note that these two 2 approaches are not exclusive.
Making a website responsive means that some elements will respond by adapting its size or other functionality according to the device’s screen size, typically the viewport width, through CSS media queries, for example, making the font size smaller on smaller devices.
@media (min-width: 601px) {
.my-class {
font-size: 24px;
}
}
@media (max-width: 600px) {
.my-class {
font-size: 12px;
}
}
A mobile-first strategy is also responsive, however it agrees we should default and define all the styles for mobile devices, and only add specific responsive rules to other devices later. Following the previous example:
.my-class {
font-size: 12px;
}
@media (min-width: 600px) {
.my-class {
font-size: 24px;
}
}
A mobile-first strategy has 2 main advantages:
It’s more performant on mobile devices, since all the rules applied for them don’t have to be validated against any media queries.
It forces to write cleaner code in respect to responsive CSS rules.
How is responsive design different from adaptive design?
Both responsive and adaptive design attempt to optimize the user experience across different devices, adjusting for different viewport sizes, resolutions, usage contexts, control mechanisms, and so on.
Responsive design works on the principle of flexibility - a single fluid website that can look good on any device. Responsive websites use media queries, flexible grids, and responsive images to create a user experience that flexes and changes based on a multitude of factors. Like a single ball growing or shrinking to fit through several different hoops.
Adaptive design is more like the modern definition of progressive enhancement. Instead of one flexible design, adaptive design detects the device and other features and then provides the appropriate feature and layout based on a predefined set of viewport sizes and other characteristics. The site detects the type of device used and delivers the pre-set layout for that device. Instead of a single ball going through several different-sized hoops, you’d have several different balls to use depending on the hoop size.
Both have these methods have some issues that need to be weighed:
Responsive design can be quite challenging, as you’re essentially using a single albeit responsive layout to fit all situations. How to set the media query breakpoints is one such challenge. Do you use standardized breakpoint values? Or, do you use breakpoints that make sense to your particular layout? What if that layout changes?
Adaptive design generally requires user agent sniffing, or DPI detection, etc., all of which can prove unreliable.
Have you ever worked with retina graphics? If so, when and what techniques did you use?
Retina is just a marketing term to refer to high resolution screens with a pixel ratio bigger than 1. The key thing to know is that using a pixel ratio means these displays are emulating a lower resolution screen in order to show elements with the same size. Nowadays we consider all mobile devices retina defacto displays.
Browsers by default render DOM elements according to the device resolution, except for images.
In order to have crisp, good-looking graphics that make the best of retina displays we need to use high resolution images whenever possible. However using always the highest resolution images will have an impact on performance as more bytes will need to be sent over the wire.
To overcome this problem, we can use responsive images, as specified in HTML5. It requires making available different resolution files of the same image to the browser and let it decide which image is best, using the html attribute srcset and optionally sizes, for instance:
<div>
<img></img>
</div>
It is important to note that browsers which don’t support HTML5’s srcset (i.e. IE11) will ignore it and use src instead. If we really need to support IE11 and we want to provide this feature for performance reasons, we can use a JavaScript polyfill, e.g. Picturefill (link in the references).
For icons, I would also opt to use SVGs and icon fonts where possible, as they render very crisply regardless of resolution.
Is there any reason you’d want to use translate() instead of absolute positioning, or vice-versa? And why?
translate() is a value of CSS transform. Changing transform or opacity does not trigger browser reflow or repaint but does trigger compositions; whereas changing the absolute positioning triggers reflow. transform causes the browser to create a GPU layer for the element but changing absolute positioning properties uses the CPU. Hence translate() is more efficient and will result in shorter paint times for smoother animations.
When using translate(), the element still occupies its original space (sort of like position: relative), unlike in changing the absolute positioning.
How would you approach fixing browser-specific styling issues?
After identifying the issue and the offending browser, use a separate style sheet that only loads when that specific browser is being used. This technique requires server-side rendering though.
Use libraries like Bootstrap that already handles these styling issues for you.
Use autoprefixer to automatically add vendor prefixes to your code.
Use Reset CSS or Normalize.css.
If you’re using Postcss (or a similar transpiling library), there may be plugins which allow you to opt in for using modern CSS syntax (and even W3C proposals) that will transform those sections of your code into corresponding safe code that will work in the targets you’ve used.
Have you ever used a grid system, and if so, what do you prefer?
Before Flex became popular (around 2014), the float-based grid system was the most reliable because it still has the most browser support among the alternative existing systems (flex, grid). Bootstrap was using the float approach until Bootstrap 4 which switched to the flex-based approach. As of writing (2020), flex is the recommended approach for building grid systems and has decent browser support.
For the adventurous, they can look into CSS Grid Layout, which uses the shiny new grid property; it is even better than flex for building grid layouts and will be the de facto way to do so in the future.