🖌️

CSS

Sections: Design, Layout, Animation, Mechanics, Problem solving

What is the difference between Responsive Design vs Adaptive Design
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.
What is the difference between Mobile-First Design vs Graceful degradation
  • Mobile-First Design (introduced by Luke Wroblewski) is an approach that prioritizes the mobile version of a website that should take into account the constraints and user browsing behavior on mobile devices.
  • The mobile-first approach is a tenet of progressive enhancement. It is the ideology that mobile design, as the hardest, should be done first. Once the mobile design questions are answered, designing for other devices will be easier.
    • What it boils down to is that, the smallest of the designs will have only the essential features, so right away you have designed the heart of your UX.
  • The opposite approach is graceful degradation. This incorporates all of the complexities right from the start, then strips them away later for smaller devices.
    • The problem with graceful degradation is that when you build the all-inclusive design right from the start, the core and supplementary elements merge and become harder to distinguish and separate. The entire philosophy runs the risk of treating mobile design as more of an afterthought since you’re “cutting down” the experience.
  • Mobile Design
What is the CSS display property? What are some ways it can be used?
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
Resetting vs Normalizing CSS
Resetting - Resetting strips all default browser styling on elements.
  • For example, margins, paddings, font-sizes of all elements are reset to be the same. You will have to redeclare styling for common typographic elements.
Normalizing - Normalizing preserves useful default styles rather than "unstyling" everything.
  • It also corrects bugs for common browser dependencies.

Resetting is useful for designs that have very customized or unconventional sites

block vs inline-block vs inline
block
⭐️Size:
  • inherits from parent
⭐️Positioning:
  • starts on a new line and does not allow adjacent HTML elements next to it
Can specify width and height:
  • true
⭐️Can be aligned with vertical-align:
  • false
Margins and paddings:
  • Respected
Float:
  • -
inline-block
Size:
  • Depends on content
Positioning:
  • Flows along with other content + allows other elements beside it.
Can specify width and height:
  • true
Can be aligned with vertical-align:
  • true
Margins and paddings:
  • Respected
Float:
  • -
inline
Size:
  • Depends on content
Positioning:
  • Flows along with other content + allows other elements beside it.
⭐️Can specify width and height:
  • false
Can be aligned with vertical-align:
  • true
⭐️ Margins and paddings:
  • Only horizontal sides respected.
⭐️Float:
  • Becomes like a block element where you can set vertical margins and padding.
relative vs fixed vs absolute vs static -ally positioned elements

A positioned element is an element whose computed position property is either relativeabsolutefixed or sticky.

static
  • The default position; the element will flow into the page as it normally would.
  • The toprightbottomleft 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 is the z-index property? And what is stacking context and how is it formed?
The z-index CSS sets the vertical stacking order of positioned elements (or elements that have a position value which is not static)
The element with a higher z-index will get stacked on top with a single stacking context
  • <span style="z-index:5">top box</span> goes on top of
  • <span style="z-index:2">middle box</span> which goes on top of
  • <span style="z-index:auto">auto box</span>
  • The stacking context is a three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user, who is assumed to be facing the viewport or the webpage. HTML elements occupy this space in priority order based on element attributes.
  • Additionally,
    • Stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts.
    • Each stacking context is completely independent of its siblings: only descendant elements are considered when stacking is processed.
    • Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.
Why would you use translate() over absolute + relative + fixed positioning ?
Both are ways to animate HTML elements using CSS
  • When an HTML element is given a relative, absolute, or fixed positioning attribute, you’ll be able to move them around by altering it’s top, right, left, bottom attributes.
  • div {
    	position: absolute || relative || fixed;
      top || bottom || left || right: <length> || <percentage> || auto || inherit;
    }
  • Similarly, you can use the translate() method to apply transformations
  • div {
    	transform: translate( <length> || <percentage>, <length> || <percentage>);
    }
There are two reasons:
  1. Performance
    • Animating positioned elements will trigger the browser to synchronously recalculate the style and layout*. This is also called reflow or layout thrashing, and is common performance bottleneck.
  2. User Experience (i.e. silky smooth animations)
  3. translate() causes the browser to create a GPU layer for the element, which allows subpixel animation, creating for a smoother
    If you want your element that has position: absolute; top: 2px; to move to position: absolute; top: 5px;, browsers will render the animation pixel by pixel:
    • top: 2px; ➡️ top: 3px; ➡️ top: 4px; ➡️top: 5px;
    And when using translate() your browser would render the animation a lot smoother:
    • translate: 0.1px; ➡️ translate: 0.2px; ➡️ translate: 0.3px; ➡️translate: 0.4px; ➡️translate: 0.5px; ➡️translate: 0.6px; ➡️translate: 0.7px; ➡️translate: 0.8px; ➡️translate: 0.9px; ➡️translate: 1px;
float vs clear
float
  • float is a positioning property, which can have the values of left , right, none and inherit.
HTML elements with the CSS float property applied remain a part of the flow of the web page.
  • distinctly different absolutely positioned page elements, which are removed from the flow of the webpage
clear
  • clear is also a positioning property ("the sister property of float"), which can have the values of both, left , right, and none
  • HTML elements with the CSS clear property applied will not move up adjacent to the float, but will move itself down past the float.
clearfix
  • If a parent element contains nothing but floated elements, its height will be collapsed to nothing. It can be fixed by clearing the float after the floated elements in the container but before the close of the container.
  • "The .clearfix hack" uses a clever CSS pseudo selector (:after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class like .clearfix to it. Then apply this CSS:
  • .clearfix:after {
      content: '.';
      visibility: hidden;
      display: block;
      height: 0;
      clear: both;
    }
Illustrated
  • float
  • image
  • clear
  • #footer {
      clear: both;			
    }
    image
BFC (block formatting context) how does it work? And why is it important?
  • A block formatting context is a part of a visual CSS rendering of a web page. It's the region in which the layout of block boxes occurs and in which floats interact with other elements.
  • Floats, absolutely positioned elements, inline-blocks, table-cells, table-captions, and elements with overflow other than visible (except when that value has been propagated to the viewport) establish new block formatting contexts.
Block formatting contexts are important for the positioning (see float) and clearing (see clear) of floats.
  • The rules for positioning and clearing of floats apply only to things within the same block formatting context.
  • Floats don't affect the layout of the content inside other block formatting contexts, and clear only clears past floats in the same block formatting context. Margin collapsing also occurs only between blocks that belong to the same block formatting context.
An HTML box establishes a BFC when it satisfies at least one of the following conditions:
  • The value of float is not none.
  • The value of position is neither static nor relative.
  • The value of display is table-celltable-captioninline-blockflex, or inline-flex.
  • The value of overflow is not visible.
What is the Box Model, and how does it work?
every element in web design is a rectangular box.
When box-sizing: content-box (default):
image

The Box Model describes how the padding, border, and margin are added to the content to create this rectangle. In other words, we can say that every box has a content area and an optional surrounding margin, padding, and border.

1. Content Box:
  • The area where your content is displayed. The width and height of this area depends on the element’s content (text, images, videos and any child elements ), and can also be set with the width and height properties
2. Padding box:
  • The padding sits around the content as white space; its size can be controlled using padding and related properties.
  • If there is no padding width defined, the padding edge is equal to the content edge.
3. Border box:
  • The border box wraps the content and any padding. Its size and style can be controlled using border and related properties.
  • If there is no border width defined, the border edge is equal to the padding edge.
4. Margin box:
  • The margin is the outermost layer, wrapping the content, padding and border as whitespace between this box and other elements. Its size can be controlled using margin and related properties.
  • If there is no margin width defined, the margin edge is equal to the border edge.
How is total width and height calculated?

Total Width = width + padding-left + padding-right + border-left + border-right + margin-left + margin-right

Total Height = height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom

When box-sizing: border-box ("the alternative CSS box model")
  • The total width and height of the box is explicit.
  • I.O.W: The width and height accounts for any border, padding, and margin — and should be deducted to find the dimensions of the content-box
These two are equivalent
.box {
  border: 5px solid rebeccapurple;
  background-color: lightgray;
  padding: 40px;
  margin: 40px;
  width: 300px;
  height: 150px;
}

.alternate {
  box-sizing: border-box;
	width: 390px;
	height: 240px
}
⭐️ Grid vs Flexbox

The CSS Grid Layout (aka “Grid”) module, is a two-dimensional grid-based layout system. The Grid Layout applies CSS rules both to a parent element (which becomes the Grid Container) and to that element’s children (which become Grid Items).

The CSS Flexbox Layout (Flexible Box) module, is a way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic (thus the word “flex”).

What is CSS selector specificity and how does it work?
MDN says
Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element.
💡
Specificity only applies when the same element is targeted by multiple declarations

When calculating specificity,

  • inline style attribute ⇒ 1,0,0,0 points ===1000 points (note: automatic win)
  • for each #id ⇒ 0,1,0,0 points === 100 points
  • for each .class ⇒ 0,0,1,0 === 10 points
  • for each <tag> element reference (like p) ⇒ 0,0,0,1 point === 1 point
The exception is !important. But not recommended
p {
    color: red !important;
}
#thing {
    color: green;
}
<p id="thing">Will be RED.</p>
Further reading
Preprocessors: SCSS, SASS — What are they and how do they work?

A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own unique syntax.

What can Sass/SCSS do that Vanilla CSS can’t?
Nested Rules:
  • Nest your CSS properties within multiple sets of {} brackets. This makes your CSS code a bit more clean-looking and more intuitive.
Variables:
  • Standard CSS has variable definitions. So what’s the deal? You can do a lot more with Sass variables: iterate them via a for-loop and generate property values dynamically. You can embed them into CSS property names themselves. It’s useful for property-name-N { … } definitions.
Better Operators:
  • You can add, subtract, multiply and divide CSS values. Sure the original CSS implements this via calc() but in Sass you don’t have to use calc() and the implementation is slightly more intuitive.
Functions:
  • Sass lets you create CSS definitions as reusable functions. Speaking of which…
Trigonometry:
  • Among many of its basic features (+, -, *, /), SCSS allows you to write your own functions.
  • You can write your own sine and cosine (trigonometry) functions entirely using just the Sass/SCSS syntax just like you would in other languages such as JavaScript.
  • Some trigonometry knowledge will be required. But basically, think of sine and cosine as mathematical values that help us calculate the motion of circular progress bars or create animated wave effects, for example.
Code Flow and Control Statements:
  • You can write CSS using familiar code-flow and control statements such as for-loops, while-loops, if-else statements similar to another languages. But don’t be fooled, Sass still results in standard CSS in the end. It only controls how property and values are generated. It’s not a real-time language. Only a pre-processor.
Mixins:
  • Create a set of CSS properties once and reuse them or “mix” together with any new definitions. In practice, you can use mixins to create separate themes for the same layout, for example.
Media Queries — What are they used for?

Media queries are useful when you want to modify your site or app depending on a device's general type (such as print vs. screen) or specific characteristics and parameters (such as screen resolution or browser viewport width).

Use Cases...
Explain CSS sprites, and how you would implement them on a page or site. What are the benefits of CSS sprites?
  • CSS sprites combine multiple images into one single larger image. It is a commonly-used technique for icons (Gmail uses it).
Implementation:
  1. Use a sprite generator that packs multiple images into one and generate the appropriate CSS for it.
  2. Each image would have a corresponding CSS class with background-imagebackground-position and background-size properties defined.
  3. To use that image, add the corresponding class to your element.
Advantages:
  • Reduce the number of HTTP requests for multiple images (only one single request is required per spritesheet). But with HTTP2, loading multiple images is no longer much of an issue.
  • Advance downloading of assets that won't be downloaded until needed, such as images that only appear upon :hover pseudo-states. Blinking wouldn't be seen.
How do you serve your pages for feature-constrained browsers? What techniques/processes do you use?
Graceful degradation
  • The practice of building an application for modern browsers while ensuring it remains functional in older browsers.
Progressive enhancement
  • The practice of building an application for a base level of user experience, but adding functional enhancements when a browser supports it.
  • Feature detection using Modernizr.
  • Use CSS Feature queries @support
How do 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.
What are the various clearing techniques and which is appropriate for what context? What problem is this meant to solve?
👎 The problem:

If a parent element contains nothing but floated elements, its height will be collapsed to nothing. It can be fixed by clearing the float after the floated elements in the container but before the close of the container.

👍Clearing Methods
The Empty Div Method:
  • The empty div method is quite literally, an empty div. <div style="clear: both;"></div>.
  • You can also use a <br /> element or some other element used, but div is the most common because...
    1. it has no browser default styling,
    2. doesn't have any special function, and
    3. is unlikely to be generically styled with CSS.
💡
This method is scorned by semantic purists since its presence has no contexual meaning at all to the page and is there purely for presentation. Of course in the strictest sense they are right, but it gets the job done right and doesn't hurt anybody.
The Overflow Method:
  • The overflow method relies on setting the overflow CSS property on a parent element.
  • If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats, effectively clearing it for succeeding elements.
💡
This method can be beautifully semantic as it may not require an additional elements. However if you find yourself adding a new div just to apply this, it is equally as unsemantic as the empty div method and less adaptable. Also bear in mind that the overflow property isn't specifically for clearing floats. Be careful not to hide content or trigger unwanted scrollbars.
The Easy Clearing Method:
  • "The .clearfix hack" uses a clever CSS pseudo selector (:after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class like .clearfix to it. Then apply this CSS:
.clearfix:after {
  content: '.';
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}
🤔Which to choose

Different scenarios call for different float clearing methods. Take for example a grid of blocks, each of different types.

image
💡
To better visually connect the similar blocks, we want to start a new row as we please, in this case when the color changes.
  • We could use either the overflow or easy clearing method if each of the color groups had a parent element.
  • Or, we use the empty div method in between each group. Three wrapping divs that didn’t previously exist or three after divs that didn’t previously exist. I’ll let you decide which is better.
image
Further reading
What is a media type? Can you give an example of an @media types other than screen?

Media types describe the general category of a given device, and there are four types of @media properties (including screen):

  • all - for all media type devices
  • print - for printers
  • speech - for screenreaders that "reads" the page out loud
  • screen - for computer screens, tablets, smart-phones etc.

Here is an example of CSS targeting printers:

  • print media type's usage:
@media print {
  body {
    color: black;
  }
}
How do you visually hide content (and make it available only for screen readers)?
  • width: 0; height: 0. Make the element not take up any space on the screen at all, resulting in not showing it.
  • position: absolute; left: -99999px. Position it outside of the screen.
  • text-indent: -9999px. This only works on text within the block elements.
How do you write efficient CSS?
Avoid key selectors that are tag and universal selectors. They match a large number of elements and browsers will have to do more work in determining if the parents do match.
  • Why?
    1. 💡
      Browsers match selectors from right (key selector) to left, and filter out elements in the DOM according to the key selector and traverse up its parent elements to determine matches. So, the shorter the length of the selector chain, the faster the browser can determine if that element matches the selector.
    2. How would the browser parse #id .class > ul a?
      • In this example, the key selector is a.
      • First, the browser finds all elements matching the key selector a
      • Then, the browser finds all ul elements on the page
      • Then filters the a elements down to just those elements that are descendants of ul elements — and so on until it reaches the leftmost selector.
What are the main advantages of using CSS preprocessors? Disadvantages?
  • 👍 Additional functionality (nested rules, variables, additional functions, trigonometry, control flow / loops / etc., mixins)
  • 👍 Facilitates maintainability by enabling DRY via additional functionality
  • 👎 Set up, and re-compilation can be slow
What is CSS BEM?
image
Using flexbox, style the HTML below to create a 3-column layout where each column takes up a col-{n} / 12 ratio of the container.
image
image
What is the difference between em and rem units?
image
What are the advantages of using CSS sprites and how are they utilized?
image
What is the difference between + and ~ sibling selectors?.
image
What is a focus ring? What is the correct solution to handle them?
image