Basics

CSS stands for Cascading Style Sheets. It is not a programming language. It allows us to style HTML documents. The extension of a CSS file is .css. In CSS, a semicolon is placed after each statement. The term "cascade" refers to how styles are applied to elements in a structured and predictable manner. When multiple styles are defined for the same element, CSS follows a set of rules to determine which style takes precedence. The hierarchy of styles can be omitted with !important (added after the command - color: blue !important;). We can create comments between /* and */ signs. Things that we write between these signs don't count as code. Comments are often used to describe the code.

We can style the HTML tags, IDs (indicated with #), and classes (marked with .). An ID has to be unique to a subpage. It is assigned to an element like this: <p id="p"></p>, and then styled in CSS: #p {...}. A class is used to style many objects on a website. An element can have many classes. They are assigned to an element like this: <p class="p p2"></p>, and then styled in CSS: .p {...}. An object can have both classes and an ID.

The * selector applies styles to all document elements, while the body selector specifically targets the <body> element and its children.

A container is typically used to wrap and structure the content on a web page, providing a centralized area to manage the layout and appearance of elements. Containers are often defined using the <div> element (I will talk about them in a moment), which acts as a block-level element that holds other content. The primary purpose of a container is to create a defined space in which content is organized, usually for better alignment, padding, or width control. By setting specific width, margin, and padding properties, a container ensures that its child elements are consistently styled and positioned.

We can write CSS code inside the <style> tags in the head of an HTML document, inline (in the style attribute of a selected element), or in an external .css file (recommended because of style integrity). We connect the external file (stylesheet) in the <head> section like this: <link rel="stylesheet" href="style.css" type="text/css">. All the examples will be written in a shortened version to avoid redundancy and improve readability (the <style> tags will be right next to the HTML content).

CSS hierarchy:

  1. Inline styles - style="color: blue;".
  2. Styles from the <style> tag - <style>p{color: blue;}</style>.
  3. Styles from a file - p{color: blue;}.
  4. The default value.

The object's ID is higher in the hierarchy than its class.

p{color: blue;}

p - a selector

color - a property (attribute)

blue - a value

Basic commands

Font

font-style Setting the font style (normal, italic, oblique).
font-variant Setting the font variant (normal, small-caps).
font-weight Setting the font thickness (lighter, normal, bold, bolder, 100-900).
font-size Setting the font size (e.g., 20px).
font-family Setting the font family (Arial, Verdana, etc.). Example: font-family: Arial, Helvetica, sans-serif; (the first available font will be chosen).
font All-in-one in this order (separated by commas): style, variant, weight, size, family. Example: font: italic small-caps bold 16px Arial;.

The all-in-one commands do not require us to provide all values but just the ones we need.

Text

color Setting the text color (#303030 (hex) or white (color name)).
text-align Aligning text (center, left, right, justify).
text-decoration Decorating text (none, underline, overline, line-through, blink).
text-indent Setting the first line indentation (e.g., 5px).
text-transform Converting all text to uppercase or lowercase (uppercase, lowercase).
letter-spacing Setting the spacing between letters (e.g., 5px).
word-spacing Setting the spacing between words (e.g., 5px).
line-height Setting the spacing between lines of text (e.g., 5px).

Background

background-color Setting the background color (#303030 (hex) or white (color name)).
background-image Setting the background image (url("image.jpg")).
background-repeat Setting on which axis will the background image repeat if it is too small (repeat, repeat-x, repeat-y, no-repeat).
background-attachment Controlling whether the background image scrolls with the page (fixed, scroll).
background-position Setting the background image position by two coordinates x, y (center, top, left, right, bottom, and numerical values, e.g., 20px). We separate the two coordinates with a space. If we provide only one value, it will apply to both axes.
background All-in-one in this order (separated by commas): color, image, repeat, attachment, position. Example: background: #303030 url("image.jpg") no-repeat fixed left top;.

Sizes

width Setting the width of an element.
height Setting the height of an element.
min-width Setting the minimum width of an element. It can increase based on content, and min-height also exists.
max-width Setting the maximum width of an element. It can decrease based on content, and max-height also exists.

Border

border-width Setting the width of all / chosen borders (thin, medium, thick). We can choose specific borders for all of these commands like this: border-top-width.
border-style Setting the style of all / chosen borders (none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset).
border-color Setting the color of all / chosen borders (#303030 (hex) or white (color name)).
border All-in-one in this order (separated by commas): width, style, color. Example: border: 2px solid #303030;.
border-radius Setting how much a corner is rounded (e.g., 5px).

Lists

list-style-type Setting the look of list's numbers, dots, etc. For <ol>: decimal, decimal-leading-zero, lower-alpha, lower-greek, lower-latin, lower-roman, upper-alpha, upper-latin, upper-roman, and so on. For <ul>: circle, disc, square. The only style for both lists is none.
list-style-position Setting the position of the list's markers (outside, inside).
list-style-image Setting an image as the list's markers (url("image.jpg")).
list-style All-in-one in this order (separated by commas): type, position, image.

Margins

margin Setting the margins (outer spacings), such as distance between containers (e.g., 20px). We can choose a specific side for the margin to apply like this: margin-top. When providing all the values at once, they are in this order: top, right, bottom, left (clockwise).
padding Setting the paddings (inner spacings), such as text spacing from the edge of a container (e.g., 20px). We can choose a specific side for the padding to apply like this: padding-top. When providing all the values at once, they are in this order: top, right, bottom, left (clockwise).

Other

cursor Setting the cursor style (auto, crosshair, default, pointer, move, text, wait, help, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize).
opacity Setting the transparency of an object (0.1, 0.2, etc.) 0 is fully invisible, and 1 is fully visible.
outline Setting the outline of an element, which is a line drawn outside the border. It does not affect the layout of the page and does not take up space. Commonly used for accessibility (like focus indication of the <input> tag). We can define its width, style, and color. Example: outline: 2px solid red;
filter Adjusting the brightness of an element (brightness(70%)).
box-sizing Controlling how the total size of an element is calculated (content-box, border-box). Use border-box to include padding and border in the total width and height of a container.
box-shadow Adding shadow to an element. Specify horizontal offset, vertical offset, blur radius, spread radius, and color (e.g., box-shadow: 2px 2px 5px 0px #000;). The inset keyword places the shadow inside the element.
column-count Specifying the number of columns an element's content should be divided into, enabling easy creation of multi-column layouts (e.g., 2).

The <div> tag

The <div> tag is a block-level container used to group content and elements for organizational and styling purposes. It does not inherently have any visual representation or semantic meaning but serves as a versatile tool for structuring web pages. Developers often use <div> to apply CSS styles or JavaScript functionality to a specific section of the page by assigning it a unique ID or class. It allows designers to layout content effectively.

Overflow

overflow-x controls the horizontal scrollbar, and overflow-y - the vertical one (visible, hidden, scroll, auto). The overflow attribute controls both scrollbars at once.


<style>
    .overflow {
        background-color: #eee;
        color: black;
        padding: 15px;
        width: 100%;
        height: 200px;
        overflow: scroll;
        border: 1px solid #ccc;
    }
</style>

<div class="overflow">
    <p>Lorem ipsum...</p>
</div>
                                    

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur non turpis lobortis, mollis purus in, luctus neque. Cras sed justo sem. Sed fermentum velit dolor, ut tincidunt ex bibendum eu. Vivamus at sagittis nunc. Morbi consequat feugiat quam vitae porta. Donec consectetur diam et vehicula facilisis. Nam vulputate purus tortor, vel varius eros imperdiet id. Ut interdum enim purus, vel hendrerit leo convallis tincidunt. Fusce et orci eget ipsum tincidunt vestibulum. Nullam sit amet suscipit est, at semper augue. In nibh est, gravida ac massa eu, mattis egestas arcu. Sed urna metus, vehicula sit amet purus a, ultricies iaculis dolor. Aliquam erat volutpat. Fusce vitae varius sapien. Suspendisse fringilla ornare neque ac mattis. Sed placerat risus eget est bibendum, sed tempor tortor ultricies. Integer vitae ornare arcu. Ut laoreet ligula ex, non porta elit pretium sed. Sed vel nunc mauris. Suspendisse ex lorem, vulputate eget ex sit amet, pellentesque lobortis est. Pellentesque sollicitudin sagittis eros et facilisis. Duis commodo est at purus aliquam laoreet. Nam facilisis consectetur nisl nec finibus. Aliquam vehicula enim eros, vitae sagittis urna egestas quis. Etiam nec turpis laoreet tortor eleifend bibendum. Nam id eros eros. Vestibulum suscipit dapibus sem, id sagittis justo malesuada non. Donec porttitor dapibus velit, eu convallis magna sodales laoreet. Proin ut consectetur quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque ut mi et odio convallis luctus. Sed ut scelerisque ipsum. Maecenas tempor varius dui, consequat efficitur diam vulputate ut. Maecenas vel ipsum vel elit fermentum vulputate vel et arcu. Nam dictum mi eu nisi egestas, vel posuere nisi commodo. Pellentesque sed felis sit amet mauris lobortis tincidunt a ut ex. Phasellus sit amet sollicitudin felis. Fusce nec ante at mauris dignissim auctor quis ut urna. Quisque bibendum purus sit amet semper vulputate. Quisque commodo diam nunc, non tempor neque sodales a. Proin vitae accumsan ipsum. Vivamus eu risus lacus. Etiam ullamcorper augue nisi, vitae ultrices lorem tempor eu. Vestibulum quam arcu, vestibulum eleifend egestas vitae, semper ut turpis. Sed non tempus odio, id viverra mi. Sed sed ultrices lorem. Curabitur vel laoreet sem. Ut euismod, massa quis convallis egestas, purus ligula feugiat ante, ac dignissim quam odio id lorem. Pellentesque tincidunt arcu id fringilla vehicula. Nunc turpis nibh, iaculis quis ex a, ullamcorper dignissim ex. Quisque condimentum, dui in lobortis mattis, ligula massa facilisis diam, ac condimentum augue purus eu justo.

Browser prefixes

When defining properties that do not work across all browsers, we need to add prefixes:

  • -webkit - for Safari and Chrome.
  • -moz - for Mozilla Firefox.
  • -ms - for Internet Explorer.
  • -o - for Opera.

Example: -moz-column-count: 2;.

Attribute selectors and custom attributes

An attribute selector is a type of selector that allows us to select and style HTML elements based on the presence or value of specific attributes. This includes both standard HTML attributes and custom attributes (also known as data attributes) that we can define for our purposes. Custom attributes are prefixed with data-. Attribute selectors are defined with square brackets.


<style>
    [data-blue]{background-color: blue;} /* all elements that have this attribute */                           
    p[data-red]{background-color: red;} /* paragraphs that have this attribute */
    [data-d="blue"]{background-color: blue;} /* all elements that have this attribute with "blue" assigned */
    [data-d="red"]{background-color: red;} /* all elements that have this attribute with "red" assigned */
    div[class*="a"]{background-color: red;} /* divs that have a class assigned, whose name has "a" in it */
</style>

<div data-blue>Lorem ipsum</div>
<p data-red>Lorem ipsum</p>
<div data-d="blue">Lorem ipsum</div>
<div data-d="red">Lorem ipsum</div>
<div class="aoo">Lorem ipsum</div>
                                    
Lorem ipsum

Lorem ipsum

Lorem ipsum
Lorem ipsum
Lorem ipsum

Using attribute selectors, we can style specific form controls, e.g., input[type="text"]. If we want to define the same style for multiple elements that do not have any relationships in the cascade, we can use commas: input[type="text"], input[type="password"].

Units

A viewport is the area of ​​the browser window. It is defined as the area in which we view the website but without the window border and possible sliders. On the other hand, the canvas can be larger than the viewport. The canvas is the entire website area, even the one that does not fit in the viewport (on the screen).

Relative units

  • em - Relative to the font size of the parent element (e.g., 1.5em).
  • rem - Relative to the font size of the root element (html) (e.g., 2rem - 2x the root font size).
  • % - Relative to the parent element's width or height (e.g., 50%).
  • vw - 1% of the viewport's width (e.g., 10vw).
  • vh - 1% of the viewport's height (e.g., 20vh).
  • vmax - Relative to the larger of the viewport's width or height.
  • vmin - Relative to the smaller of the viewport's width or height.

Absolute units

  • px - Pixels, an absolute unit based on screen resolution (e.g., 16px).
  • in - Inches, an absolute physical measurement (e.g., 1in).
  • cm - Centimeters, an absolute physical measurement (e.g., 2cm).
  • mm - Millimeters, an absolute physical measurement (e.g., 5mm).

When no unit is given, it means pixels (not always).

The calc() function allows us to perform calculations to determine property values dynamically. It can be used to combine different units and to create more flexible layouts and designs. We can use calc() to calculate widths, margins, padding, or font sizes based on a combination of fixed and relative units. Example: width: calc(100% - 20px);. We can use these arithmetic operators: +, -, *, /.