CSS Usages

Why CSS?

Basically, CSS (Cascading Style Sheets) is used to control the presentation and layout of HTML documents. It allows developers to separate the content of a webpage from its design, making it easier to maintain and update the appearance of multiple pages at once.

CSS is used to define the visual style of HTML elements, such as colors, fonts, spacing, and positioning. It provides a way to create consistent and visually appealing designs across different web pages and devices.

CSS is also used to create responsive designs that adapt to different screen sizes and devices. By using media queries and flexible layouts, developers can ensure that their websites look good and function well on desktops, tablets, and smartphones.


CSS Selectors, Attributes, Properties

CSS Selectors

CSS selectors are used to target specific HTML elements and apply styles to them. There are several types of CSS selectors, including:

  • Universal selector: Targets all elements on the page (e.g., *).
  • Element selectors: Target specific HTML elements by their tag name (e.g., p, h1, div).
  • Class selectors: Target elements with a specific class attribute (e.g., .my-class).
    • It is necessary to use a period (.) before the class name, and the class name should be unique within the page.
    • Also, multiple classes can be applied to a single element by separating them with spaces.
    • Elements to select need to have corresponding 'class' attribute.
  • ID selectors: Target elements with a specific ID attribute (e.g., #my-id).
    • It is necessary to use a hash symbol (#) before the ID name, and the ID name should be unique within the page.
    • Elements to select need to have corresponding 'id' attribute.
    • The ID selector has a higher specificity than class selectors, meaning that if an element has both a class and an ID, the styles defined by the ID selector will take precedence over those defined by the class selector.
    • Also, it's not possible for a element to have multiple IDs, but can have multiple classes.
  • Attribute selectors: Target elements based on their attributes (e.g., [type="text"]).
  • Pseudo-class selectors: Target elements based on their state or position (e.g., :hover, :first-child).
  • Pseudo-element selectors: Target specific parts of an element (e.g., ::before, ::after).
You can use comma to select multiple elements at once.

CSS Attributes

CSS attributes are used to define the styles that will be applied to the selected elements. Some common CSS attributes include:

  • color: Sets the text color of an element.
  • background-color: Sets the background color of an element.
  • font-size: Sets the size of the text.
  • font-family: Sets the font type for the text.
  • margin: Sets the space outside an element.
  • padding: Sets the space inside an element, between the content and the border.
  • border: Sets the border style, width, and color of an element.
  • width and height: Set the dimensions of an element.
  • display: Controls how an element is displayed (e.g., block, inline, flex).
  • position: Controls how an element is positioned on the page (e.g., static, relative, absolute, fixed).

CSS Properties

CSS properties are the specific values assigned to the attributes to define the appearance of the elements. For example:

  • color: red; (sets the text color to red)
  • background-color: #f0f0f0; (sets the background color to a light gray)
  • font-size: 16px; (sets the font size to 16 pixels)
  • margin: 10px; (sets a 10-pixel margin around the element)
  • padding: 5px; (sets a 5-pixel padding inside the element)
  • border: 1px solid black; (sets a 1-pixel solid black border around the element)

Example CSS Code

p, .my-class, #my-id {
    color: red;
    background-color: #f0f0f0;
    font-size: 16px;
    margin: 10px;
    padding: 5px;
    border: 1px solid black;
}

Stylesheet Types

There are three main types of stylesheets in CSS:

  • Inline styles: Styles applied directly to an HTML element using the "style" attribute. Example: <p style="color: red;">This is a red paragraph.</p>
  • Internal stylesheets: Styles defined within a <style> tag in the <head> section of an HTML document. Example: <style> p { color: red; } </style>
  • External stylesheets: Styles defined in a separate .css file and linked to the HTML document using the <link> tag. Example: <link rel="stylesheet" href="styles.css">

CSS Specificity

CSS specificity is a set of rules that determine which styles are applied to an element when multiple styles conflict. There are two types of specifity, one regarding user/author/browser - defined styles (Hierarchy 1), and the other regarding the selectors used in the CSS rules (Hierarchy 2). The latter is more important for developers to understand, as it directly affects how their styles are applied to elements on a webpage.

Specificity hierarchy 1 is as follows:

  • User-defined styles (e.g., user's custom browser settings, such as high contrast mode.)
  • Author-defined styles (e.g., styles defined by the website's developer in the CSS files.)
  • Browser-defined styles (e.g., default styles applied by the browser to HTML elements, such as the default font size and color for paragraphs.)

The specificity hierarchy 2 is as follows:

  • !important declarations(e.g., p { color: red !important; }) have the highest specificity.
  • Inline styles (e.g., style="color: red;") have the second highest specificity.
  • ID selectors (e.g., #my-id) have higher specificity than class selectors, attribute selectors, and pseudo-classes.
  • Class selectors (e.g., .my-class), attribute selectors (e.g., [type="text"]), and pseudo-classes (e.g., :hover) have higher specificity than element selectors and pseudo-elements.
  • Element selectors (e.g., p, h1, div) and pseudo-elements (e.g., ::before, ::after) have the lowest specificity.

When multiple styles are applied to same element, the style with the highest specificity will take precedence. If two styles have the same specificity, the one that appears last in the CSS will be applied.


CSS Styles


CSS Font Styles

CSS font styles are used to control the appearance of text on a webpage. Some common CSS font styles include:

  • font-family: Specifies the font type for the text (e.g., Arial, Times New Roman, sans-serif).
    • Standard Format: font-family: <font name1, font name2, ...>
    • browser will first try to apply the first font, and if it's not available, it will try the next one.
  • font-size: Specifies the size of the text (e.g., absolute: 16px, xx-small, small, medium, large, x-large, xx-large, relative: 1.2em, 120%, 1.5rem).
    • Absolute Units(px, xx-small, small, medium, large, x-large, xx-large): These specify the exact size of the text in pixels or predefined sizes.
    • Relative Units(em, rem, %): These specify the size of the text relative to the parent element's font size (em), the root element's font size (rem), or a percentage of the parent element's font size (%).
  • font-weight: Specifies the thickness of the text (e.g., normal, bold, 100-900 (400:normal, 700:bold)).
  • font-style: Specifies the style of the text (e.g., normal, italic, oblique(tilts the text. italic has its tilted font already designed.)).

CSS Web Fonts

CSS web fonts allow developers to use custom fonts on their websites, even if the user doesn't have those fonts installed on their device. This is done by linking to a font file hosted on a server or using a font service like Google Fonts.

To use a web font, you can include a link to the font file in your HTML document's <head> section, and then use the font-family property in your CSS to apply the font to specific elements.

Example:

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">

CSS Icon Fonts

Icon fonts are a way to display icons using web fonts. They allow you to use icons as if they were regular text, making them easy to style and manipulate with CSS.

You can find a variety of icon fonts online, such as Font Awesome and Bootstrap Icons.

CSS Text Styles

CSS text styles are used to control the appearance of text on a webpage. Some common CSS text styles include:

  • color: Specifies the color of the text. (e.g., #000000, red, rgba(255, 0, 0, 0.5))
    • Hexadecimal: #000000
    • Named colors: red
    • RGB: rgb(255, 0, 0)
    • RGBA: rgba(255, 0, 0, 0.5)
  • text-align: Specifies the horizontal alignment of the text (e.g., left, right, center, justify, start, end, match-parent).
    • start: aligns the text to the start of the line (left for left-to-right languages, right for right-to-left languages).
    • end: aligns the text to the end of the line (right for left-to-right languages, left for right-to-left languages).
    • left: aligns the text to the left side of the element.
    • right: aligns the text to the right side of the element.
    • center: centers the text within the element.
    • justify: aligns the text to both the left and right sides of the element, adding extra space between words as necessary.
    • match-parent: inherits the text alignment from its parent element.
  • text-decoration: Specifies the decoration added to the text (e.g., none, underline, overline, line-through).
  • line-height: Specifies the height(distance) of each line of text (e.g., normal, 1.5, 2em).
    • normal: The default line height, which is typically around 1.2 times the font size.
    • number: A unitless value that is multiplied by the element's font size to determine the line height (e.g., 1.5 means 1.5 times the font size).
    • length: A specific length value, such as pixels (px), ems (em), or rems (rem) (e.g., 20px, 1.5em, 2rem).
    • percentage: A percentage value that is relative to the element's font size (e.g., 150% means 1.5 times the font size).
  • text-shadow: Specifies the shadow effect added to the text (e.g., none, 2px(horizontal) 2px(vertical) 5px(blur) rgba(0, 0, 0, 0.5)).
    • none: No shadow effect is applied to the text.
    • h-shadow: The horizontal offset of the shadow. A positive value moves the shadow to the right, while a negative value moves it to the left.
    • v-shadow: The vertical offset of the shadow. A positive value moves the shadow down, while a negative value moves it up.
    • blur: The blur radius of the shadow. A larger value creates a more blurred shadow, while a smaller value creates a sharper shadow.
    • color: The color of the shadow. This can be specified using named colors, hexadecimal values, RGB, or RGBA.
  • letter-spacing: Specifies the space between characters in the text (e.g., normal, 1px, 0.1em).
  • word-spacing: Specifies the space between words in the text (e.g., normal, 1px, 0.1em).
  • text-transform: Specifies the capitalization of the text (e.g., none, capitalize, uppercase, lowercase).
    • none: No transformation is applied to the text.
    • capitalize: The first letter of each word is converted to uppercase.
    • uppercase: All letters in the text are converted to uppercase.
    • lowercase: All letters in the text are converted to lowercase.
    • full-width: All characters are converted to their full-width equivalents(meaning, each character's height and width become same length).
  • text-indent: Specifies the indentation of the first line of text (e.g., 0, 2em, 20px).
  • white-space: Specifies how whitespace is handled in the text (e.g., normal, nowrap, pre, pre-wrap, pre-line).
  • word-wrap: Specifies how long words should be broken and wrapped onto the next line (e.g., normal, break-word).
  • word-break: Specifies how words should break when reaching the end of a line (e.g., normal, break-all, keep-all).
  • text-overflow: Specifies how overflowed text is displayed (e.g., clip, ellipsis, string).
  • direction: Specifies the text direction (e.g., ltr, rtl, inherit). ltr: left-to-right, rtl: right-to-left, inherit: inherits the direction from its parent element.
  • unicode-bidi: Specifies how the text should be displayed when dealing with bidirectional text (e.g., normal, embed, isolate, bidi-override, isolate-override, plaintext).
  • hyphens: Specifies how words should be hyphenated when breaking lines (e.g., none, manual, auto).
  • text-align-last: Specifies the alignment of the last line of text in a block (e.g., auto, left, right, center, justify).
  • text-justify: Specifies the justification method for text (e.g., auto, none, inter-word, inter-character, distribute, kashida).
  • text-emphasis: Specifies the emphasis marks added to the text (e.g., none, circle, dot, sesame, accent).
  • text-emphasis-position: Specifies the position of the emphasis marks relative to the text (e.g., over, under, right, left).
  • text-emphasis-style: Specifies the style of the emphasis marks (e.g., none, circle, dot, sesame, accent).
  • text-emphasis-color: Specifies the color of the emphasis marks (e.g., inherit, currentColor, red, #ff0000).
  • text-orientation: Specifies the orientation of the text in vertical writing modes (e.g., mixed, upright, sideways, sideways-right).
  • text-combine-upright: Specifies how multiple characters should be combined into a single upright character in vertical writing modes (e.g., none, all, digits, letters, full-width).
  • text-rendering: Specifies how the text should be rendered (e.g., auto, optimizeSpeed, optimizeLegibility, geometricPrecision).
  • text-anchor: Specifies the alignment of the text relative to a given point (e.g., start, middle, end).
  • writing-mode: Specifies the direction in which the text is written (e.g., horizontal-tb, vertical-rl, vertical-lr, sideways-rl, sideways-lr).

CSS List Styles

CSS List Styles are used to decorate and adjust location of bullets in lists.

  • list-style-type: Changes bullet shape to selected type. Available choices are listed below.
    • disc: •
    • circle: ○
    • square: ■
    • decimal: 1, 2, 3, 4, ...
    • decimal-leading-zero: 01, 02, 03, 04, ...
    • lower-roman: i, ii, iii, iv, v, ...
    • upper-roman: I, II, III, IV, V, ...
    • lower-alpha (or lower-latin): a, b, c, d, ...
    • upper-alpha (or upper-latin): A, B, C, D, ...
    • none: deletes bullet.
  • list-style-image: Changes bullet shape to selected image. (e.g., list-style-image: url('images/dot.png');)
  • list-style-position: Changes location of list elements. (e.g., inside, outside(default))
    • inside: indents the list.
    • outside: does not indent the list. Default value.
  • list-style: Combination of previous properties (list-style-type, list-style-image, list-style-position). (e.g., list-style: decimal inside;)

CSS Table Styles

CSS Table Styles are used to decorate and adjust table properties.

  • caption-side: You can relocate title from top to bottom. (e.g., bottom, top (default))
  • border: Draws border for elements. Widely used for various elements. (e.g. 1px solid black).
  • border-spacing: Adjust margin lengths between cells. (e.g., 1em(horizontal margin length) 3em(vertical margin length))
  • border-collapse: Selects whether <table> tag and <td> tag's border should be collapsed(combined) to one. Default value is 'seperate'. (e.g. seperate(default), collapse)

CSS Block Model

Every html element can be classified to two classes.
One is block-level-element, which takes up whole horizontal space on its own. Another is inline-level-element, and it just takes up the space its content need to have.

You can check whether each element is block-level-element or not here.

You can adjust the size of block elements using the width and height properties, whereas inline elements cannot.


Block Model's Basic Structure

The structure of the box-type elements is the same as shown in the photo at right. You can use various properties to adjust its size, background color, location etc.

Box Model Structure

Adjusting Size of Elements


Box Model Structure
  • width: Adjusts width of block elements.
    • Uses %, px, auto(default) as its value.
  • height: Adjusts height of block elements.
    • Uses %, px, auto(default) as its value.

One problem is that both width and height properties adjust 'content' area, not the whole area the element takes. To change the whole size of element including padding and margin, you can use 'box-sizing' property.

  • box-sizing:Set whether width and height property apply to the whole area element takes, or just the content.
    • Uses border-box, content-box(default) as its value.

How to Decorate Box Elements

You can use various properties to decorate elements, such as giving shadow effect, color background, color border and more. Let's further find out what properties there are.


1. Shadow Effects

You can use this property to give shadow effect for a element.

Usage

box-shadow: (horizontal offset) (vertical offset) (blur radius) (spread radius) (color) (inset or outset)

  • horizontal offset: Adjusts horizontal location of the shadow. Positive value relocates the shadow to right. Necessary value.
  • vertical offset: Adjusts vertical location of the shadow. Positive value relocates the shadow to upward.
  • blur radius: Adjusts the blur level of the element. Positive value increases amount of blur, while negative value is not allowed (Default is zero.).
  • spread radius: Adjusts how far the shadow should spread out. Positive and negative value increases and decreases the shadow size (spread level) respectively. Defulat is 0.
  • color: Changes color of the shadow. Defulat is black.
  • inset or outset: Changes whether the shadow effect applies inside or outside. Default is outset unless keyword inset is applied.

2. Border Effects

You can use this property to give and decorate borders of a element.

Usage

border-style:(style);
border-width: (width);
border-color: (color);

  • style: Used to change border style(type). Available styles are listed below.
    • none: Default value. No border.
    • hidden: Border exists but hidden.
    • solid: Solid line.
    • dotted: Dotted line.
    • dashed: Dashed line.
    • double: Two solid lines. border-width property adjusts the distance of two lines.
    • groove: See below.
    • inset: See below.
    • outset: See below.
    • ridge: See below.
  • width: Used to adjust the width of border.
  • color: Used to change the color of border.
Example
Solid Red
Dotted Orange
Dashed Yellow
Double Green
Groove Lightblue
Inset Blue
Outset Purple
Ridge Gray

You can use 'border' property to set all these three simultaneously.

border: (width) (style) (color)
border-(top/bottom)-(left/right)-radius: (radius)

Used to curve the vertex. top/bottom, left/right is only used when adjusting one vertex.

Example
0.5em
1em
1.5em
2em
2.5em
3em
3.5em
4em

3. Margins

Margin is area around the border. There are also properties to re-size and decorate margin.

Usage

margin-(top/bottom/left/right): (size1)(size2)(size3)(size4)

Used to adjust the size of margins. You can specify which side to edit individually (top, bottom, left, or right) or provide multiple values. Using just 'margin' and providing multiple values applies them in the order of top, right, bottom, and left (clockwise). Using a single value applies it to all four sides.

You can use 'margin-top', 'margin-bottom', 'margin-left', 'margin-right' to change each side respectively.

Tips
  • To align an element to the center of the page, you can use margin-left:auto and margin-right:auto to relocate it.
  • When you align multiple elements vertically, larger margin will collapse with (or override) the smaller one (without overlapping the content). For example, if you have an element with a 30px bottom margin and another with a 40px top margin stacked vertically, the space between them will be 40px rather than 70px (due to margin collapsing).

4. Paddings

Padding is area between border and content. Adjusting its size and other properties are identical to margin.

Usage

padding-(top/bottom/left/right): (size1)(size2)(size3)(size4)

Used to adjust the size of paddings. You can specify which side to edit individually (top, bottom, left, or right) or provide multiple values. Using just 'padding' and providing multiple values applies them in the order of top, right, bottom, and left (clockwise). Using a single value applies it to all four sides.

CSS Layouts

Changing Element Type

There are also situations when inline elements should function as block elements or vice versa.

display:(block, inline, inline-block, none)

Floating an Element

float:(left, right, none)

Make an element float from normal flow of the document and display it at chosen location.

An element that comes after a floated element will also float unless the 'clear' property is applied.

clear:(left, right, both)

Example

There's one massive object in the universe that absorbs everything it encounters - the blackhole. This thing is created by a supernova - death of a massive star. Even light can't escape from it. Some scientists suggest that in the far future we might be able to time travel using a blackhole. We don't actually know whether this will really happen or not, but studying this fascinating object will improve our overall technologies.


Locating an Element

position:(static/relative/absolute/fixed/sticky)
left:(value)
right:(value)
top:(value)
bottom:(value)

'position' property sets the initial standard of an element.

After setting initial location after using 'position' property, you can use 'left, right, top, bottom' to move the element.


CSS Background

Setting Background Color and Background Range

1. Background Color

background-color:(color)

Sets the background-color.

2. Background Color

background-clip:(border-box/padding-box/content-box)

Sets the range of background.

  • border-box: Applies background to border-box area.
  • padding-box: Applies background to padding-box area.
  • content-box: Applies background to content-box area.

Setting Background Image and Gradation and How to Repeat Them

1. Background Image

background-image:url('image-file-path')

Set's the background-image. When the given image is smaller than the size of element, background image is repeated. Repeating method is determined through 'background-repeat' property.

2. Repeating the Background

background-repeat:(repeat/repeat-x/repeat-y/no-repeat)

Set's the way how the background will be repeated.

  • repeat: Default value. Repeats along both x-axis and y-axis.
  • repeat-x: Repeats along x-axis.
  • repeat-y: Repeats along y-axis.
  • no-repeat: No repeating. Indicates only once.

3. Positioning Background Image

background-position: (left | center | right | <percentage> | <length>)(top | center | bottom | <percentage> | <length>)

  • horizontal offset: Sets horizontal location.
  • vertical offset: Sets vertical location.

4. Applying Background to Other Area

background-origin:(content-box | padding-box | border-box)

Set's where the background should apply. It can be content-box, padding-box(default), border-box.

  • content-box: Background is applied to content box only.
  • padding-box: Background is applied to padding-box. Default value.
  • border-box: Background is applied to border-box.

5. Fixing Background Location

background-attachment: (scroll | fixed)

Background image is fixed when this property is used.

  • scroll: The background image scrolls along with the page content.(Default)
  • fixed: The background image stays fixed in place while the rest of the page scrolls.

6. Using 'background' Property to Adjust 1~5 At Once

background:url("filepath") (repeat) (position) (attachment)

Input sequence can be different.

7. Changing Background Size

background-size:(auto | contain | cover | <size> | <percentage>)

You can also change background-size.

  • auto: Display background image in its original size. Default value.
  • contain: Resize the image so that background image can fit into the element.
  • cover: Resize the image so that background image can cover the whole element.
  • <size> Set width and height of the image. When only one value is given, height is automatically calculated and this value is set as width.
  • <percentage> Resize the image proportional to the element depending on given percentage.

8. Gradation

There are two types of gradation - 'Linear Gradation', 'Circular Gradation'. Former one gradates linearly, latter the circularly.

(1) Linear Gradation

linear-gradient(to (<direction> or <angle>), (starting color), (mid color1), (mid color2)..., (ending color))

repeating-linear-gradient(to (<direction> or <angle>), (starting color), (mid color1), (mid color2)..., (ending color))

  • direction: Use keywords (left/right, top/bottom) for direction. Keywords can be used together for diagonal directions.
  • angle: Use angle for direction. The angle increases in clockwise direction, starting from upside (+y axis).
  • starting color: Starting color for gradients.
  • mid color(n): Mid colors for gradients. Comes after starting color.
  • ending color: Ending color for gradients. Comes after mid colors.

Use repeating-linear-gradient to repeat gradation.

(2) Circular Gradation

radial-gradient((<shape>) (size) at (starting color), (mid color1), (mid color2),... (ending color))

  • shape: Either 'epllipse' or 'circle' can be used as its value. Defaykt us 'ellipse'.
  • size: Used to adjust the size of ellipse or circle. Its value can be 'closest-side', 'closest-corner', 'farthest-side', 'farthest-corner'.
    • closest-side:
  • starting color: Starting color for gradients.
  • mid color(n): Mid colors for gradients. Comes after starting color.
  • ending color: Ending color for gradients. Comes after mid colors.

Use repeating-radial-gradient to repeat gradation.


CSS Responsive Web

Viewport

Viewport is the visible area of a web page on a device. It can be adjusted using 'meta' tag in HTML.

<meta name="viewport" content="(width | height | user-scalable | initial-scale)">

  • width: Sets the width of the viewport. It can be set to a specific value (e.g., 600px) or to 'device-width' to match the device's screen width.
  • height: Sets the height of the viewport. Similar to width, it can be a specific value or 'device-height'.
  • user-scalable: Determines whether users can zoom in and out. It can be set to 'yes(value = 1)' or 'no (value = 10)'.
  • initial-scale: Sets the initial zoom level when the page is first loaded. A value of 1.0 means no zoom, while values greater than 1.0 ~ 10.0 zoom in and values less than 1.0 zoom out.

At most cases, <meta name="viewport" content="width=device-width, initial-scale=1"> is used.


How to Make Elements Responsive

1. Using Units for Responsive Elements

Viewport Units: vw, vh, vmin, vmax

  • vw: 1vw equals 1% of the viewport's width.
  • vh: 1vh equals 1% of the viewport's height.
  • vmin: The smaller value between vw and vh.
  • vmax: The larger value between vw and vh.

2. Using Units for Responsive Texts

Viewport Units for Text: em, rem

  • em: 1.2em means the font for this element will be 1.2times bigger than its parent element.
  • rem: 1.2em means the font for this element will be 1.2times bigger than its root element.

3. Using 'object-fit' for Responsive Images

You can use object-fit property to make images responsive.

object-fit:(fill | contain | cover | none | scale-down)

  • fill: Resize the image to fully fill its surrounding element.
  • contain: Maintain original image width and height ratio, while ensuring the entire image fits within its surrounding element (may leave empty space).
  • cover: Maintain original image width and height ratio, while fully filling its surrounding element.
  • none: Maintain original image width and height (not ratio, its original fixed width and height).
  • scale-down: Acts like none or contain, whichever yields a smaller image size.

4. Using Media Query for Responsive Layout

Media Query allows users to use different CSS files depending on the deviced used.

@media (only | not) (media type) and (condition 1) and (condition 2) and ...

@media only handheld and (min-width: 800px) and (max-width: 1500px)

  • only | not: 'only' is used to make unsupported older browsers to skip this media query, and 'not' is used to exclude certain media type that will not use this CSS Stylesheet.
  • media type: In what device this CSS Stylesheet will be used. Possible media types are listed below.
    • all: All media types included. Default value.
    • print: For printing devices.
    • screen: For computer and smartphone screens, tablets included.
    • tv: For televisions.
    • aural: For devices that reads the screen aloud.
    • braille: For braille tactile feedback devices.
    • handheld: For handheld devices. This media type is deprecated and should be avoided(Used for old phones).
    • projection: For projectors.
    • tty: For teletypewriter devices.
    • embassed: For braille printing devices.