CSS Questions Flashcards

1
Q

What is CSS selector specificity and how does it work?

A

In CSS, specificity is a measurement of relevance based on the type and order of CSS selectors in a document. In cases when an HTML element or a group of elements is targeted by multiple CSS selectors, the rules of CSS specificity tell the web browser which CSS declarations should be applied.

The “specificity hierarchy,” which lists selector types from the highest specificity to the lowest specificity:

  1. ID selectors: ID selectors are the most specific kind of selector. They select an element based on its ID attribute (e.g., #my-id).
    *Class selectors, attribute selectors, and pseudo-class selectors: These three selector types have equal specificity.
    *Class selectors select all elements in a CSS class (e.g., .my-class).
    *Attribute selectors select all elements with a given attribute (e.g., p[target]).
  2. Pseudo-class selectors select elements only when in a special state, like visited or hover (e.g., button:hover).
  3. Type selectors: These select all HTML elements that have a given node name and have the syntax element (e.g., div).
  4. Universal selector: The universal selector (*) has no effect on specificity.

Rule 1: The CSS selector with higher specificity applies.
Rule 2: If CSS selectors have equal specificity, then the last rule in the document applies.
Rule 3: Inline CSS has the highest specificity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s the difference between “resetting” and “normalizing” CSS?Which would you choose, and why?

A

Normalizing retains the default styles that are useful and removes those that are not whereas the reset removes all the styles of the browser. In reset, we will have to re declare all the styles after resetting the browser whereas, normalizing will keep the required styles and only removes the unwanted ones.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe Floats and how they work.

A

he float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow (in contrast to absolute positioning).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Describe z-index and how stacking context is formed.

A

Z Index ( z-index ) is a CSS property that defines the order of overlapping HTML elements. Elements with a higher index will be placed on top of elements with a lower index. Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).

A stacking context is created when an element is positioned and assigned a z-index value other than auto , or when an element has an opacity value less than 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Describe BFC (Block Formatting Context) and how it works.

A

A block formatting context (BFC) 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. A block formatting context is created by at least one of the following: The root element of the document ( <html> ).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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

A

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.
In large projects, having a utility .clearfix class will be very helpful. overflow: hidden might clip children if the children is higher than the parent and is not very ideal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would you approach fixing browser-specific styling issues?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you serve your pages for feature-constrained browsers?What techniques/processes do you use?

A
  • 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.
  • Use caniuse.com to check for feature support.
    Autoprefixer for automatic vendor prefix insertion.
    *Feature detection using Modernizr.
    *Use CSS Feature queries @support
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the different ways to visually hide content (and make it available only for screen readers)?

A

These techniques are related to accessibility (a11y).

  • 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. This is a widely used and famous trick, but it comes with some downsides like causing performance issues, so you might want to consider using text-indent: 100% instead.
  • Meta tags. For example by using Schema.org, RDF, and JSON-LD.
  • WAI-ARIA. A W3C technical specification that specifies how to increase the accessibility of web pages.

Even if WAI-ARIA is the ideal solution, I would go with the absolute positioning approach, as it has the least caveats, works for most elements and it’s an easy technique.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Have you ever used a grid system, and if so, what do you prefer?

A

Flex is the recommended approach for building grid systems and has decent browser support. But I am almost confident that with the broader adoption of CSS Grid, it will turn into the main layout standard.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Have you used or implemented media queries or mobile specific layouts/CSS?

A

Yes. An example would be transforming a stacked pill navigation into a fixed-bottom tab navigation beyond a certain breakpoint.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Are you familiar with styling SVG?

A

(inline CSS) 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can you give an example of an @media property other than screen?

A

all - for all media type devices
print - for printers
speech - for screenreaders that “reads” the page out loud

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are some of the “gotchas” for writing efficient CSS?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the advantages/disadvantages of using CSS preprocessors? Describe what you like and dislike about the CSS preprocessors you have used.

A

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.
Sass features like loops, lists, and maps can make configuration easier and less verbose.
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.
Not writing currently and potentially usable CSS. For example, by using something like postcss-loader with webpack, you can write potentially future-compatible CSS, allowing you to use things like CSS variables instead of Sass variables. Thus, you’re learning new skills that could pay off if/when they become standardized.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How would you implement a web design comp that uses non-standard fonts?

A

Likes:

Mostly the advantages mentioned above.
Less is written in JavaScript, which plays well with Node.

Dislikes:

I use Sass via node-sass, which is a binding for LibSass written in C++. I have to frequently recompile it when switching between node versions.
In Less, variable names are prefixed with @, which can be confused with native CSS keywords like @media, @import and @font-face rule.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Explain how a browser determines what elements match a CSS selector.

A

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>

18
Q

Describe pseudo-elements and discuss what they are used for.

A

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

A

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.
20
Q

What does * { box-sizing: border-box; } do? What are its advantages?

A

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.

21
Q

What is the CSS display property and can you give a few examples of its use?

A

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

22
Q

What’s the difference between inline and inline-block?

A

block = fills up the width of it’s parent container, starts on a new line.

inline-block = depends on content, flows with other content and allows other elements beside it.

inline = depends on content, flows with other content and allows other elements beside it, cannot specify width and height, only horizontal sides respected.

23
Q

What’s the difference between the “nth-of-type()” and “nth-child()” selectors?

A

nth-child() Selector: This selector is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child, regardless of the type, of its parent.

nth-of-type() Selector: This Selector is used to style only those elements which are the nth number of children of its parent element. Any n may be a number, a keyword, or a formula.children

24
Q

What’s the difference between a relative, fixed, absolute and statically positioned element?

A

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.

25
Q

What existing CSS frameworks have you used locally, or in production? How would you change/improve them?

A

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.

26
Q

Have you used CSS Grid?

A

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.

27
Q

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

A

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.

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.

28
Q

Have you ever worked with retina graphics? If so, when and what techniques did you use?

A

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

29
Q

Is there any reason you’d want to use translate() instead of absolute positioning, or vice-versa? And why?

A

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.

30
Q

How is clearfix css property useful?

A

The clearfix property allows a container to wrap its floated children. Without a clearfix, a container will not wrap around its floated children and will collapse, just as if its floated children had been positioned absolutely.

Replacing the clearfix hack with a single line of code using a new display mode rule known as flow-root.

.container {
display: flow-root;
}

31
Q

Can you explain the difference between px, em and rem as they relate to font sizing?

A

Use px for small, fixed-size elements like borders or shadows. Use em for typography and other scalable elements that need to change size relative to their parent element. Use rem for scalable typography and responsive layouts that need to change size relative to the root element.

32
Q

Can you give an example of a pseudo class? Can you provide an example use case for a pseudo class?

A

A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, the pseudo-class :hover can be used to select a button when a user’s pointer hovers over the button and this selected button can then be styled.

33
Q

What is the difference between a block level element and an inline element. Can you provide examples of each type of element?

A

Inline elements only cover the space as bounded by the tags in the HTML element. Block elements have top and bottom margins. Inline elements don’t have a top and bottom margin. Examples of block elements - <p>,<div>,<hr>. Examples of inline elements - <a>,<b>,<br></br></b></a>

34
Q

What is the difference between CSS Grid and Flexbox? When would you use one over the other?

A

The main difference is that you can use CSS Grid to create two-dimensional layouts. In contrast, you can only use Flexbox to create one-dimensional layouts. That means you can place components along the X- and Y-axis in CSS Grid and only one axis in Flexbox. With Bootstrap, you can create a grid using only HTML. With Flexbox, you must use HTML and CSS.

35
Q

How will you check for coding errors in CSS?

A

Use CSS LINT to Fix Errors and Warnings

To process code, simply copy and past it in to the area provided and hit Lint. Errors are identified with a red warning sign while warnings are identified with yellow ones. CSS code containing errors and warning are highlighted after the table.

36
Q

What is the difference between display none and visibility hidden?

A

visibility:hidden hides the element, but it still takes up space in the layout. display:none removes the element from the document. It does not take up any space.

37
Q

How do you center align a div tag in CSS?

A

<div>
<!-- Content of the div goes here -->
</div>

.center-div {
width: 300px; /* Adjust the width as needed */
margin-left: auto;
margin-right: auto;
}

or give it a class=”wrapper” then

.wrapper {
display: flex;
justify-content: center;
}

for flexbox

38
Q

How do you vertically align a div in CSS?

A

give it a class=”wrapper” then

.wrapper {
display: flex;
align-items: center;
}

for flexbox

39
Q

Suggest three ways to reduce the load time of a page.

A

Choose a performance-optimized hosting solution.
Compress and optimize your images.
Reduce your redirects.
Cache your web pages.
Enable browser caching.
Use asynchronous and defer loading for your CSS and JavaScript files.
Minify CSS, JavaScript, and HTML.

40
Q

Suggest any three position-property attributes.

A

static.
relative.
fixed.
absolute.
sticky.