Previously: part 1 - general — part 2 - html
In this post I’m going to work through some of the CSS questions posed in the Front-end Interview Questions repo.
Q. What is CSS selector specificity and how does it work?
-
Specificity (and the cascade, given equal specificity) determines what CSS rules will be applied to an element. In order of precedence:
- Type selectors (e.g.
<h1>
) - Class selectors (e.g.
.post
), attribute selectors and pseudo classes (e.g.[type="password"]
and:disabled
) - ID selectors (e.g.
#main
) - Inline styles (e.g.
<span style="color:#0f0">...</span>
) !important
declarations on your style rules
- Type selectors (e.g.
Q. What's the difference between "resetting" and "normalizing" CSS? Which would you choose, and why?
-
Reset style sheets aim to remove all browser styles, bringing every element to an even level, upon which you'd layer your site's own styles. That is, all headers, body text, strong, italics, etc. will be stripped of size, decoration, margins, and padding.
A normalize style sheet aims to make all those values consistent among browsers, while maintaining some of the browsers' sane choices. For example, an
<h1>
will be 16px, bold, and have a margin and padding. It's opinionated, so you have to agree with their choices or override them.I think I'd use one or the other depending on the scope of the project I'm working on. For a small site where I can more easily pick and choose which modules I'd like to include, I'd probably opt for a normalize CSS. For a large enterprise site where we'd have standards that span across the organization, I'd probably go for a reset. Though resets can be annoying given the layer upon layer of cascade that you have to sift through while debugging, the flattened and predictable result is great to build upon.
Q. Describe floats and how they work.
-
After the world figured out that tables were intended for data, we needed another way to achieve columnar layouts. Floats did this pretty well, but came with some headaches. To its parent, a floated element pretty much doesn't exist. That is, its dimensions are ignored and unless the parent has a block formatting context, it will collapse. Floats were great at some things. For instance, throwing out a list of thumbnails all floated left will stack them in line, and once the width of its parent is reached, they'll intelligently wrap themselves.
clear
ing floats is where a lot of developers would encounter trouble. You could add a non-semantic block-level element after your floats and have itclear: both;
, but this screwed up all our beautiful semantic, non-presentational markup. It wasn't until this beauty was widely distributed that working with floats became easy and common:1 2 3 4 5
.clearfix::after { content: ""; display: table; clear: both; }
Q. Describe z-index and how stacking context is formed.
-
The stacking context defines the context from which elements with a different
z-index
value will be layered along the z axis. Given a common stacking index, the lower thez-index
, the further from the user the element will be. MDN has a great analogy to help conceptualize the stacking context:An easy way to figure out the rendering order of stacked elements along the Z axis is to think of it as a "version number" of sorts, where child elements are minor version numbers underneath their parent's major version numbers.
Some of the common CSS properties which will trigger a stacking context:
- An element with a position of
absolute
orrelative
- An element with an
opacity
less than 1 - An element whose
transform
,filter
orclip-path
properties have a value other than none
- An element with a position of
Q. Describe BFC (Block Formatting Context) and how it works.
-
I think anyone who has implemented a layout in CSS has tangled with this, whether they knew the term or not. I guess the best way to describe it is having a box that contains its child elements (both floated and non-floated) without collapsing entirely or collapsing margins on its children. Common ways to achieve this are setting
overflow: auto;
on the parent, or using the clearfix:after
hack (though this won't fix your margins collapsing).There's also a new property,
display: flow-root;
, designed to fix just this annoying issue, but its support is still pretty limited Q. How would you approach fixing browser-specific styling issues?
-
The two best strategies I can think of are Using vendor prefixes where required, and using conditional comments to target IE (which, let's face it, is usually the problem). Beyond that, frequenting sites like Caniuse to get a solid understanding of what you can and can't do is always necessary.
Q. How do you serve your pages for feature-constrained browsers?
-
I always try to build my pages using progressive enhancement, layering cool stuff on top of base-level functionality. Beyond that, using Polyfills is a great way to get browsers on an even keel.
Q. What are the different ways to visually hide content (and make it available only for screen readers)?
-
A common thing we used to do before webfonts were around was to use image replacement on (typically) headers. You can still provide the text on the page with its appropriate semantics, and use
text-indent: -9999px;
to throw the content outside the viewport. Then you'd set abackground-image
in your CSS to provide the pretty fonts. The plaintext will still be accessible to screen readers.Another way, if the content is intended just for screen readers, is to position it off screen:
1 2 3 4
.help-text { position: absolute; left: -9999px; }
Or by turning it into an almost non-existent box:
1 2 3 4 5 6 7 8
.help-text { clip: rect( 0 0 0 0); height: 1px; width: 1px; margin: -1px; overflow: hidden; position: absolute; }
Q. Have you ever used a grid system, and if so, what do you prefer?
-
Nope! I've been reading about them a bit lately, and frankly they sound freaking great!
Bootstrap, which I'm using for the first time with any regularity here, also has added a grid system to its package. I will probably fool with that to change this layout from its current flex-base to grid.
Q. Are you familiar with styling SVG?
-
Very little! On an older version of the LinkedIn profile, I used RaphaelJS to generate SVG for some small graphs, so I did very little manual editing.
Q. Can you give an example of an
@media
property other than screen?-
Sure, you can do
@media print
to alter styles for when a user prints a page. Q. What are the advantages/disadvantages of using CSS preprocessors?
-
My only experience with a preprocessor is SCSS, which we used at LinkedIn during my last year or so there. For a large organization dealing with the challenges of fractured code-bases, attempting to standardize iconography, typography, and layout, and making tools that are easy for all developers to use them consistently, SCSS was great! We had mixins to do common things like clearfix, variables to provide consistent fonts and sizes, and ways to size containers so that they'd adhere to the same media queries used throughout the site.
My major complaint in using these things was the extent to which it abstracted the CSS rules. It was great that we finally had a simple and easy way to implement standards across the company. But it makes developers lack awareness of potential bloat created by throwing too many mixins around, and it distances us from what's really going on in our CSS, leading to over-reliance and ultimately an unfortunate ignorance (except on the part of the standards creators within the org).
Q. Explain how a browser determines what elements match a CSS selector.
-
A browser will work from right-to-left when matching a CSS selector. That is, given the rule:
1 2 3
.main section .time { background-color: #ccc; }
The browser will first seek out any elements with a classname of
.time
, then traverse up the DOM tree to look for an ancestor<section>
element, and then finally traverse up again looking for an ancestor with a classname of.main
. This traversal allows it to quickly discard non-matches or only partial matches. Q. Describe pseudo-elements and discuss what they are used for (also looking at pseudo-classes here)
-
Pseudo-elements are used to select specific parts of an element. The selectors are pretty self-explanatory. Here are some that are commonly-used:
::first-letter
::first-line
::after
::before
Pseudo-classes are used to select only in a certain state. Some commonly-used selectors are:
:active
:checked
:disabled
:focus
:hover
:invalid
:read-only
:required
:valid
:visited
Q. Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
What does* { box-sizing: border-box; }
do? What are its advantages?-
Believe it or not, box sizing was one thing that good ol' IE6 got right. It adhered to what is now called
border-box
sizing. That is, if you stated an element's width as 200px, then the overall width of that element was 200px, including borders and padding. Competing browsers at the time (and the default box-sizing method for CSS today) used thecontent-box
method, which stated that padding and border were added to the declared width of an element. Enter in all the backslash hacks to get IE to play nice with your floated layouts. Ugh.Fortunately, sanity took hold, and we agreed upon the universal reset that works great:
1
* { box-sizing: border-box; }
This wonderful rule tells every element to include in its width calculation an element's border and padding, giving developer's a predictable and level playing field.
All right, I think that covers enough material for this post. There are more questions remaining in the repo, but I think I’ve touched on a few of the subjects already that they’re asking about.