CSS Concepts - The one and only guide you need

weifengnusceg

WEI FENG

Posted on December 2, 2021

CSS Concepts - The one and only guide you need

"I'm just summarizing my CSS learning routine here, your follow will be my motivation to update. Hope it will help you to improve your understanding towards CSS as well. Feel Free to check the rest of my content as well(updates regularly)"




Table Of Contents

1. CSS selector Priority
2. Inheritable and non-inheritable properties in CSS
3. Difference between display's block, inline and inline-block
4. How to hide the elements
5. What's the difference between link and @import
6. Transition and Animation
7. Pseudo class and pseudo element
8. How to understand requestAnimationframe
9. Content box vs Border box
10. Why Moving Elements With Translate() Is Better Than position:absolute Top/left
11.How do you understand CSS Sprites
12.What are the measures to optimize CSS performance
13.Why are we using css preprocessor and postprocessor
14.How to determine whether an element has appeared in our viewport
15.Understand the media query
16.When does z-index not work
17.CSS layout unit
18.How to achieve a two column layout
19.How to achieve a three column layout
20.Horizontal and vertical centering
21.Understanding Flex box model
22.Responsive Design
23.Position and Floating


Other Contents

HTML - The one and only guide you need (in progress)
React Concepts Part.1 - The one and only guide you need
React Concepts Part.2 - The one and only guide you need
Browser Concepts - The one and only guide you need
Web Optimization Concepts - The one and only guide you need
Computer Network Concepts - The one and only guide you need


1. CSS selector Priority

The CSS selector priority is classified in to few different categories, each carries a different weightage. We can calculate the actual priority by summing up all the selectors' weightage.

Selector Syntax Weightage
Inline Style style="color 1000
Id selector #id 100
class selector .classname 10
attributes selector d[ref=“abc”] 10
pseudo class selector li:first-child 10
HTML tag selector div 1
pseudo element selector li:after 1
  • In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!
p {
  background-color: red !important;
}
Enter fullscreen mode Exit fullscreen mode
  • If two styles applied have the same priority, the latter one will be selected.

2. Inheritable and non-inheritable properties in CSS

1. non-inheritable properties

  • Display

  • Text attributes : vertical-align、text-decoration、 text-shadow、 white-space、 unicode-bidi

  • Box model attributes: width、height、margin、border、padding

  • Background attributes: background、background-color、background-image、background-repeat、background-position、background-attachment

  • Position attributes: float、clear、position、top、right、bottom、left、min-width、min-height、max-width、max-height、overflow、clip、z-index

  • Generated content attributes: content、counter-reset、counter-increment

  • **Outline style attributes: **outline-style、outline-width、outline-color、outline

  • Page style attributes:size、page-break-before、page-break-after

  • Audio style attributes:pause-before、pause-after、pause、cue-before、cue-after、cue、play-during

2. inheritable properties

  • font attributes: font-family、font-weight、font-size、font-style

  • text attributes: text-indent、text-align、line-height、
    word-spacing、letter-spacing、text-transform、color.

  • Visibility

  • List Layout attributes: list-style

  • cursor

3. Difference between display's block, inline and inline-block

  • block: block starts on a NEW line and takes up the full width available. So that means block elements will occupy the entire width of its parent element.

  • inline: displays the element inline or on the same line. In other words, inline elements do NOT start on a new line and only takes up as much width as its content.

  • inline-block: It’s essentially the same thing as inline, except that you can set height and width values.

4. How to hide the elements

  • display: none: such element will not be rendered, thus it will not take up any space in the page, and the event binded to such element will not be triggered.

  • visibility: hidden: the element will still hold in the page and it will respond to the events.

  • opacity: 0: set the transparency of the element to 0, behaves the same as visibility: hidden

  • position: absolute: use absolute position to move the element outside of the viewport.

  • z-index:negative value: use other elements to fully cover it.

  • transform: scale(0,0): scale the size of the element to 0,0 such element will still exist in the page, however it will not listen to the events binded.

5. What's the difference between link and @import

These are both used to reference external CSS files.

  • link is an html tag which can load more than just css files. @import on the other hand can only load css.

  • link can load the css at the same time as the webpage is loading, @import can only load css after the webpage has been completed loaded.

  • Javascript can mutate the link attributes by accessing the DOM, @import does not support such way.

6. Transition and Animation

  • transitions: For a transition to take place, an element must have a change in state, and different styles must be identified for each state. The easiest way for determining styles for different states is by using the :hover, :focus, :active, and :target pseudo-classes.

  • animations: when more control is required, transitions need to have multiple states. In return, this is why we need animation. It does not need to be triggered by any events and the animation can be looped. We can set multiple key frame points by using @keyframe

7. Pseudo class and pseudo element

Pseudo-classes act as simple selectors in a sequence of selectors and thereby classify elements on non-presentational characteristics, pseudo-elements create new virtual elements.

8. How to understand requestAnimationframe

There used to be just one way to do a timed loop in JavaScript: setInterval(). If you needed to repeat something pretty fast (but not as-fast-as-absolutely-possible like a for loop), you’d use that. For the purposes of animation, the goal is sixty “frames” per second to appear smooth, so you’d run a loop like this:

setInterval(function() {
  // animiate something
}, 1000/60);

Enter fullscreen mode Exit fullscreen mode

Now there is a better way by using requestAnimationframe

The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.

Your callback routine must itself call requestAnimationFrame() again if you want to animate another frame at the next repaint. requestAnimationFrame() is 1 shot. The number of callbacks is usually 60 times per second.

*What are the advantages *

  • Save the CPU resources : With the animation implemented by SetTinterval, when the page is hidden or minimized, SetTinterval still performs animation tasks in the background. Since the page is in an invisible or unavailable state at this time, refreshing the animation is meaningless and completely wastes CPU resources.

The RequestAnimationFrame is completely different. When the page processing is not activated, the screen refresh task of the page will also be suspended by the system. Therefore, the RequestAnimationFrame that follows the system will also stop rendering. When the page is activated, the animation will stay from the last time. Continuing execution wherever it is, effectively saving CPU overhead.

  • Throttling : In high-frequency events (resize, scroll, etc.), in order to prevent multiple function executions in one refresh interval, RequestAnimationFrame can ensure that the function is executed only once in each refresh interval, so as to ensure fluency , It can also save the cost of function execution better. It is meaningless when the function is executed multiple times within a refresh interval, because most displays refresh every 16.7ms, and multiple draws will not be reflected on the screen.

How to throttle requestAnimationFrame to a specific frame rate

  • Reduce DOM operations: requestAnimationFrame will collect all DOM operations in each frame and complete it in one repaint

Why we shouldn't use setTimeout to control animation:

  • Since setTimeout is a asynchronous task, it will only be executed when all the synchronous task are done, there is always a time delay.

  • Its fix time period will not exactly match the screen refreshing rate which leads to loss of frame.

9. Content box vs Border box

  • content-box: The width & height of the element only include the content. In other words, the border, padding and margin aren’t part of the width or height. This is the default value.

  • border-box: The padding and border are included in the width and height.

Boxmodel

10. Why Moving Elements With Translate() Is Better Than position:absolute Top/left

Translate is a method in transform property. Changing the transform or opacity will not trigger the browser to reflow and repaint, it will only trigger compositions.

However, changing the absolute positioning will trigger a re-layout, which will trigger re-paint and composititon. The transform ask the browser to create a GPU layer for the element, but changing the absolute positioning will use the CPU. Therefore translate() is more efficient and can shorten the drawing time of smooth animation. When translate changes its position, the element still occupies its original space, and this will not happen with absolute positioning.

11.How do you understand CSS Sprites

CSS Sprites are a means of combining multiple images into a single image file for use on a website, to help with performance.

We can use background-image,background-repeat,background-position
to located the image.

Pros:

  • It can minimize the http request that client side has to make for retrieving image resources from the server.

  • Combining multiple image into one will also reduce the image size

Cons:

  • Require precise measurements on each image's size.

  • When some part of the image has changed, we have to edit the combined image.

12.What are the measures to optimize CSS performance

  • Loading performance:
  1. compress CSS file to reduce file size

  2. use single css property instead of shorthand property

  3. do not use @import, use link instead

  • Selectors:
  1. Use key selectors instead of Descendant combinator as the latter will iterate through all its descendants on the tree.

  2. When using ID selector, don't add unnecessary selectors

  3. do not use * selector

  4. use class selector instead of HTML tag selector

  5. avoid repeatly assigning styles to elements, make use of the inheritable properties.

  • Rendering performance:
  1. use float and position carefully as they consume a lot of resources.

  2. avoid frequent rerendering

  3. use CSS spirte efficiently

13.Why are we using css preprocessor and postprocessor

  • css preprocessor: less, sass, stylus

  • postprocessor: postCss

Reason for use:

  • To make a clear CSS structure, easy to expand.

  • It can easily prevent different browers' syntax difference.

  • Multiple inheritance can be easily achieved.

  • Perfectly compatible with CSS code and can be applied to old projects.

14.How to determine whether an element has appeared in our viewport

  • window.innerHeight is the viewport height

  • document.body.scrollTop || document.documentElement.scrollTop is the distance that brower has scrolled.

  • imgs.offsetTop is the distance of the element's top to the top of the document

If img.offsetTop < window.innerHeight + document.body.scrollTop` || document.documentElement.scrollTop that means the img has already shown up in the viewport.

15.Understand the media query

Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for a type of device, they look at the capability of the device.

Media queries can be used to check many things, such as:

width and height of the viewport
width and height of the device
orientation (is the tablet/phone in landscape or portrait mode?)
resolution
Using media queries are a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).

16.when does z-index not work

The z-index property only works on elements with a position value other than static (e.g. position: absolute;, position: relative;, or position: fixed).

It will not be functioning properly if :

  • Parent container's position is relative

  • the element with z-index has also been set with float

17.CSS layout unit

CSS units can be separated in the following categories:

  • Absolute units

  • Font relative units

  • Viewport relative units

Absolute units:

Some units depend on certain absolute values and are not affected by any screen size or fonts. These units display may vary depending on different screen resolutions, as they depend on DPI (dots per inch) of screens.

These units are:

  • px (pixels)
  • in (inches)
  • cm (centimeter)
  • mm (millimeter)
  • pc (picas)
  • pt (points)

Font relative units:

There are some units which depend on the font size or font family of the document or its parent level elements. This includes units like:

  • em
  • rem
  • ex
  • ch

Viewport relative units:

There are a few units that depend on the viewport height and width size, such as:

  • vh (viewport height)
  • vw (viewport width)
  • vmin (viewport minimum)
  • vmax (viewport maximum)

Percentage(%) unit does not belong to any category above.

18.How to achieve a two column layout

Two column layout usually refers to a layout which has a fix width left column and auto fill right column

1.Float left element to the left, set the width to 200px, set the margin-left of the right element to the width of left element.

.outer {
height: 100px;
}
.left {
float: left;
width: 200px;
background: tomato;
}
.right {
margin-left: 200px;
width: auto;
background: gold;
}

2.make use of the absolute position, before that we have to set the position property of the parent container to anything other than static. Then set the left element's position to absolute with 200px width. Follow by right element's margin-left to 200px.

.outer {
position: relative;
height: 100px;
}
.left {
position: absolute;
width: 200px;
height: 100px;
background: tomato;
}
.right {
margin-left: 200px;
background: gold;
}

3.Use the flex layout, set left element width to 200px, set right element flex property to 1

.outer {
display: flex;
height: 100px;
}
.left {
width: 200px;
background: tomato;
}
.right {
flex: 1;
background: gold;
}

19.How to achieve a three column layout

Three column layout refers to having the left and right element with fixed width, middle element will auto fill the gap.

1.Use absolute position, set left element to a certain width. Set right element's top and right attribute to 0 so it will stick to the right side of the container. Lastly set the margin-left and margin-right of the centered element to the respective width of left and right element.

`.outer {
position: relative;
height: 100px;
}

.left {
position: absolute;
width: 100px;
height: 100px;
background: tomato;
}

.right {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 100px;
background: gold;
}

.center {
margin-left: 100px;
margin-right: 200px;
height: 100px;
background: lightgreen;
}`

2.Use flex layout, set left and right element with a fixed width, let centered element's flex: 1

`.outer {
display: flex;
height: 100px;
}

.left {
width: 100px;
background: tomato;
}

.right {
width: 100px;
background: gold;
}

.center {
flex: 1;
background: lightgreen;
}`

20.Horizontal and vertical centering

  • use the absolute position, set left and top to 50% so that the left corner of the element will appear in the center of the element. Use translate to adjust the center point of the child element to match the parent's.

.parent{position: relative;}
.child {position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}

  • Use flex layout, set align-items:center and justify-content:center

.parent {
display: flex;
justify-content:center;
align-items:center;
}

21.Understanding Flex box model

Flex is a new value added to the CSS display property. Along with inline-flex it causes the element that it applies to in order to become a flex container, and the element's children to each become a flex item. The items then participate in flex layout, and all of the properties defined in the CSS Flexible Box Layout Module may be applied.
Get your hands on experience in MDN

Image description

Image description

22.Responsive Design

Responsive Web design is a website that can be compatible with multiple terminals, instead of making a specific version for each terminal.

The basic principle is to use media query (@media) query to detect different device screen sizes for processing.

About compatibility: The page header must have the viewport declared by meta.

<meta name="’viewport’" content="”width=device-width," initial-scale="1." maximum-scale="1,user-scalable=no”"/>

23.Position and Floating

Read the BFC documentation to continue

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.
Formatting contexts affect layout, but typically, we create a new block formatting context for the positioning and clearing floats rather than changing the layout, because an element that establishes a new block formatting context will:

contain internal floats.
exclude external floats.
suppress margin collapsing.

In progress...

In progress...

💖 💪 🙅 🚩
weifengnusceg
WEI FENG

Posted on December 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related