CSS

Source: https://github.com/yangshun/front-end-interview-handbook/blob/master/questions/css-questions.md#describe-floats-and-how-they-work

CSS selector specificity

The browser determines what styles to show on an element depending on the specificity of CSS rules. We assume that the browser has already determined the rules that match a particular element.

Among the matching rules, the specificity, four comma-separate values, a, b, c, d are calculated for each rule based on the following:

  1. a is whether inline styles are being used. If the property declaration is an inline style on the element, a is 1, else 0.

  2. b is the number of ID selectors.

  3. c is the number of classes, attributes and pseudo-classes selectors.

  4. d is the number of tags and pseudo-elements selectors.

The resulting specificity is not a score, but a matrix of values that can be compared column by column. When comparing selectors to determine which has the highest specificity, look from left to right, and compare the highest value in each column. So a value in column b will override values in columns c and d, no matter what they might be. As such, specificity of 0,1,0,0 would be greater than one of 0,0,10,10.

Cases of equal specificity: the latest rule is the one that counts (the lower rule in your style sheet)

I would write CSS rules with low specificity so that they can be easily overridden if necessary.

References

"resetting" and "normalizing" CSS

  • Resetting - Resetting is meant to strip all default browser styling on elements. For e.g. 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.

I would choose resetting when I have a very customized or unconventional site design such that I need to do a lot of my own styling and do not need any default styling to be preserved.

References

floats

Float is a CSS positioning property.

Floated elements remain a part of the flow of the page, and will affect the positioning of other elements (e.g. text will flow around floated elements), unlike position: absolute elements, which are removed from the flow of the page.

The CSS clear property can be used to be positioned below left/right/both floated elements.

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 clearfix to it. Then apply this CSS:

.clearfix:after {
  content: ' ';
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}

Alternatively, give overflow: auto or overflow: hidden property to the parent element which will establish a new block formatting context inside the children and it will expand to contain its children.

References

Block Formatting Context (BFC)

A Block Formatting Context (BFC) is part of the visual CSS rendering of a web page in which block boxes are laid out.

Floats, absolutely positioned elements, inline-blocks, table-cells, table-captions, and elements with overflowother than visible (except when that value has been propagated to the viewport) establish new block formatting contexts.

A BFC is an HTML box that 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-cell, table-caption, inline-block, flex, or inline-flex.

  • The value of overflow is not visible.

In a BFC, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch).

Vertical margins between adjacent block-level boxes in a BFC collapse. Read more on collapsing margins.

References

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. Hence 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.

BEM (Block Element Modifier) methodology recommends that everything has a single class, and, where you need hierarchy, that gets baked into the name of the class as well, this naturally makes the selector efficient and easy to override.

Be aware of which CSS properties trigger reflow, repaint, and compositing. Avoid writing styles that change the layout (trigger reflow) where possible.

References

How a browser determines what elements match a CSS selector.

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.

Example: with 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.

References

Advantages / disadvantages of using CSS preprocessors

Advantages:

  • CSS is made more maintainable.

  • Easy to write nested selectors.

  • Variables for consistent theming. Can share theme files across different projects.

  • Mixins to generate repeated CSS.

  • Splitting your code into multiple files. CSS files can be split up too but doing so will require an HTTP request to download each CSS file.

Disadvantages:

  • Requires tools for preprocessing. Re-compilation time can be slow.

Pseudo-elements

Keyword added to a selector that lets you style a specific part of the selected element(s).

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. It's not really possible to draw a triangle with just CSS styles without using an additional HTML element.

References

The box model

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.

References

* { box-sizing: border-box; }

  • 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.

References

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 widthand height

Yes

Yes

No. Will ignore if being set.

Can be aligned with vertical-align

No

Yes

Yes

Margins and paddings

All sides respected.

All sides respected.

Only horizontal sides respected. Vertical sides, if specified, do not affect layout. Vertical space it takes up depends on line-height, even though the border and padding appear visually around the content.

Float

-

-

Becomes like a block element where you can set vertical margins and paddings.

relative, fixed, absolute and static

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.

References

Coding a website to be responsive vs Mobile-first strategy

Note that these two 2 approaches are not exclusive.

Making a website responsive means the 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.

Responsive design vs 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.

References

Last updated