CSS

Bulruno
9 min readMar 13, 2020

--

What is CSS selector specificity and how does it work?

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.

In the cases of equal specificity: the latest rule is the one that counts. If you have written the same rule into your stylesheet (regardless of internal or external) twice, then the lower rule in your style sheet is closer to the element to be styled, it is deemed to be more specific and therefore will be applied.

I would write CSS rules with low specificity so that they can be easily overridden if necessary. When writing CSS UI component library code, it is important that they have low specificities so that users of the library can override them without using too complicated CSS rules just for the sake of increasing specificity or resorting to !important.

Describe floats and how they work.

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.

Describe 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 overflow other than visible (except when that value has been propagated to the viewport) establish new block formatting contexts.

Knowing how to establish a block formatting context is important, because without doing so, the containing box will not contain floated children. This is similar to collapsing margins, but more insidious as you will find entire boxes collapsing in odd ways.

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.

What are the various clearing techniques and which is appropriate for what context?

  • Empty div method - <div style="clear:both;"></div>.
  • Clearfix method — Refer to the .clearfix class above.
  • overflow: auto or overflow: hidden method - Parent will establish a new block formatting context and expand to contains its floated children.

Explain CSS sprites, and how you would implement them on a page or site.

CSS sprites combine multiple images into one single larger image.

How to use it:

  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-image, background-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.

Are you familiar with styling SVG?

Yes, there are several ways to color shapes (including specifying attributes on the object) using inline CSS, an embedded CSS section, or an external CSS file. Most SVG you’ll find around the web use inline CSS, but there are advantages and disadvantages associated with each type.

Basic coloring can be done by setting two attributes on the node: fill and stroke. fill sets the color inside the object and stroke sets the color of the line drawn around the object. You can use the same CSS color naming schemes that you use in HTML, whether that's color names (that is red), RGB values (that is rgb(255,0,0)), Hex values, RGBA values, etc.

<rect
x="10"
y="10"
width="100"
height="100"
stroke="blue"
fill="purple"
fill-opacity="0.5"
stroke-opacity="0.8"
/>

The above fill="purple" is an example of a presentational attribute. Interestingly, and unlike inline styles like style="fill: purple" which also happens to be an attribute, presentational attributes can be overriden by CSS styles defined in a stylesheet. So, if you did something like svg { fill: blue; } it would override the purple fill we've defined.

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.

Describe pseudo-elements.

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.

Can you explain the difference between coding a website to be responsive versus using a mobile-first strategy?

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.

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.

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.

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 is the CSS display property and can you give a few examples of its use?

none: Does not display an element. All child elements are also no longer displayed. The document is rendered as if element did not exist in the document tree.

block: The element consumes the whole line in the block direction (horizontal)

inline: Elements can be laid out besides each other.

inline-block: Similiar to inline, but allows some block properties like width and height.

table: Behaves like <table> element.

table-row: Behaves like <tr> element

table-cell: Behaves like <td> element.

list-item: Behaves like a <li> element which allows it to define list-style-type and list-style-position.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response