DEV Community

Cover image for The Art of Styling: A Comprehensive Guide to Cascading Style Sheets(CSS)
Bhabani Sankar
Bhabani Sankar

Posted on

The Art of Styling: A Comprehensive Guide to Cascading Style Sheets(CSS)

What is CSS?

  • CSS stands for Cascading Style Sheets.
  • Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation (look and feel) of a web page written in HTML. It defines how HTML elements should be displayed on screen, paper, or in other media.
  • CSS saves a lot of work. It can control the layout of multiple web pages all at once.

Cascading: The term "cascading" refers to how styles are applied to elements in a hierarchical manner. If multiple styles apply to the same element, the "cascading" nature determines which style takes precedence. It follows a set of rules based on specificity, importance, and source order.

Styles :

  • Styles define a set of attributes that are used to make HTML more interactive and responsive.
  • Styles use an object model to format HTML elements and make them more interactive.
  • Object keeps all relative data and logic together.
  • Object enables features like a) Reusability b) Separation c) Extensibility d) Maintainability e) Testability etc..

Sheets: CSS is written in separate files (stylesheets) that can be linked to HTML documents, allowing for better organization and maintainability.

CSS Syntax

  • Object is a key and value collection enclosed in a block "{ }"..

    {
    Key : value;
    Key : value;
    }

    • Key refers to style attribute name.
    • There are various style attributes like color, width, height, margin, padding etc..

Styles can be defined for HTML elements in 3 ways.
a) Inline Styles
b) Embedded Styles
c) External Style Sheets

Inline Styles:

  • Styles are defined for HTML elements individually by using a "style" attribute.

    <h1 style="color:red; font-family:Arial; border:1px solid black">

  • Inline styles are faster in rendering.

  • You can't reuse the styles.

Embedded Styles:

  • Styles are defined for HTML elements using a <style> container.
  • You can embed style container in page.
  • It enables easy reusability and extensibility.
  • However it is slow in rendering when compared to inline.

Syntax:
<style>
selector
{
attribute: value;
}
</style>

External Style Sheets

  • You can configure styles in a separate style sheet.
  • Style sheets have extension ".css"
  • You can link style sheet to any page.
  • You can access styles across pages.

CSS Selectors

  • Selector is required for styles that are defined in embedded or external file.
  • A selector selects HTML element in page in order to apply given set of styles.
  • Selectors are of various types
  1. Primary Selectors
  2. Rational or Relational Selectors
  3. Structural Selectors
  4. Attribute Selectors
  5. Dynamic Pseudo Classes
  6. Root Selector
  7. Language Selector
  8. Universal Selector etc..

Primary Selectors:

  1. Type Selector
  2. ID Selector
  3. Class Selector

Type Selector:

  • It refers to element name.
  • It applies styles to all occurrences of element in page.
  • You can't ignore for any specific occurrence.

Syntax:
h1, p, div, span, li
{
}

ID Selector:

  • Every element can use an ID reference.
  • You can configure styles using ID.
  • ID is accessible with "#".
  • You can choose occurrence where you want to apply the styles.

Syntax:
#text-style {
}
<h1 id="text-style">

  • Every HTML element can have only one ID reference.
  • You can't apply multiple set of styles to one element using ID.

Class Selector:

  • It is defined using class attribute.
  • It is accessible using ".className".
  • You can choose specific occurrence.
  • It allows multiple inheritance.
  • You can configure multiple classes for one element.

Syntax:
.className{
}
<div class="className1 className2 className3..">

Rational or Relational Selectors:
-These selector default with parent and child elements as well as with elements that have relation.

  • Relation like adjacent, below, above, before, after, first, last etc..

Descendent Selector --
-Targets all tags under specified parent. It includes any level hierarchy.
-It defines the parent element and the child element by using
space.
Syntax:
parentElement childElement {
}

Child Selector --
-It applies effects only to the direct child of parent element.
Syntax:
Parent > child {
}

Adjacent --

  • It defines effects to an element which is specified immediately after current element.
  • It is not parent and child, it is one below another.
  • It will apply only to the first adjacent element. Syntax: FirstElement + adjacentElement { }

General --

  • It defines effects to all elements which are specified after the current element. Syntax: FirstElement ~ AdjacentElements { }

Attribute Selectors:

  • Several elements in HTML are presented by using attribute of tag. <input type="button"> <input type="radio">
  • “type” is attribute.
  • We have to apply effects based on attribute and value.

Syntax:
tagName[“attribute”] { }
tagName[“attribute=value”] { }

  • Attribute selectors can be defined with conditions.
  • Effects are applied only to attribute that match the given condition.

[attribute="val"]
-- Equal specifies that it should be exact match.

[attribute^="val"]
-- It refers the value starting with specified term.

[attribute$="val"]
-- It specifies that the value ending with given term.

[attribute*="val"]
-- It matches the term at any location.

[attribute|="val"]
-- Name starts with specified term and separated with "-".

[attribute~="val"]
-- Name start with specified term and contain blank space.

Dynamic Pseudo-Classes:

  • Dynamic indicates that the effect can change according to state and situation.
  • Pseudo indicates that it is not referring to exactly the element which is having the same name as selector name.
  • The selector name and the element if effects may differ. Syntax: link - not <link> element, it refers to <a> class/Id/type: pseudoClass { }

:link -- Specifies effect for Hyperlink.
:visited -- It defines effects for visited links.
:hover -- It defines effects when mouse pointer is over element.
:active -- It defines effects when link is in active state.
:focus -- It defines effects when element get focus.

Syntax:

Element:Link { }
#heading:hover {}
.txtName:focus { }
Enter fullscreen mode Exit fullscreen mode

Target pseudo class --
:target :-

  • It defines effects to any element when it becomes target of a link.
  • You can implement in intra document navigation.

The Element state pseudo-classes --

  • Element state indicates the state of element like enabled, disables, readonly,checked. :enabled -- It defines effects when element is enabled. :disabled -- It defines effects when element is disabled. :read-only -- It defines effects when element is set to read-only. :checked -- It defines effects when element is checked.

The Element validation state pseudo classes:

  • HTML 5 provides pre-defined form validations like require, email, url, pattern etc.
  • CSS can use HTML 5 validations to verify the state valid or not and can apply effects.

:valid -- It defines effects for element if is value is valid against the
validation defined. Validation can be verified by using:

  • Minlength
  • Maxlength
  • Required
  • Pattern
  • Email
  • URL etc.

:invalid -- It defines effect for element when it is invalid.
:in-range -- It defines effects for element when input value is within the specified range.
:out-of-range -- It defines effects for element when input value is out of given range.
-Range is verified with “min and max” values defined for input
element.
:required -- It defines effects to element when it verified with required
error.
-It is not validating required, It is just verifying whether the required defined or not.
:optional --If it is not defined with required validation then it is treated as optional.

Structural Selectors:
-You can target your effects based on the position of element in parent and child hierarchy.

:first-child -- It defines effects only for first child element.
:last-child -- It defines effects only for last child element.
:nth-child(LevelNumber) -- It defines effects only to specific child element that occurs at given level.
-Level number starts with 1.
-Index number starts with 0.
-You can also define the pre-set values like ‘even & odd’ to apply effects based on even and odd occurrences.
:nth-of-type(LevelNumber[n]) -- It will repeat the effect for every nth occurrence.
:nth-of-type(2n) -- It will repeat the effect for every 2nd occurrence.
:nth-of-type(2n+startNumber) -- It will start with specific level.
:nth-last-of-type(n) -- It will apply effect for every nth occurrence from bottom.
:nth-last-child(n) -- It will apply from bottom without repeating.
:root -- It refers to root of document, which is 'body'.
:empty -- If any element is empty, without any content then its will define the given effects.You can configure for containers like <div>, <span>,<td>, <dd>, <p> etc.

Pseudo-Element Selectors:
::first-line -- Effects for first line in paragraph.
::first-letter -- Effects for first character.
::before -- Effect or content to add before the current element.
::after -- Effect or content to add after the current element.
::placeholder -- It will apply effects for placeholder.
::selection -- It will apply effects for selection.

Language Selector:

  • It defines effects based on lang configured for element.
  • If you page is multi lingual then you can define effects to content based on specific language. ":lang()"

Universal Selector:

  • It is defined by using "*" that represents all.
  • It apply effects to all elements.

CSS Comments:

  • Comments are used to explain the code, and may help when you edit the source code at a later date.
  • Comments are ignored by browsers.
  • A CSS comment is placed inside the <style>element, and starts with /* and ends with */.
  • You can add comments wherever you want in the code.

CSS Colors:
CSS Colors

  • Colors in CSS can be defined by using 3 techniques.
  • Color Name
  • Hexadecimal color code
  • RGB Color methods.
  • CSS supports 16 million colors.
  • Standard color names are few.
  • You can directly define the color name or color shade name. Syntax: h2{ color:green; } h2{ color:lightgreen; }

Hexadecimal color code:

  • The primary colors are “Red, Green & Blue”.
  • All colors are derived from primary colors.
  • Hexadecimal allows to define multiple color shades.
  • Hexadecimal colors have a combination or 3 or 6 chars with prefix “#”
  • Hexadecimal number system is 16 base number system.
  • We use 16 different values to mix and create a color shade.
  • Hexadecimal color code uses the values 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
  • 0 is minimum and f is maximum.
  • Color code have 3 or 6 places other than #
  • If it is 3 then “#RGB” R - Red value G - Green value B - Blue value
  • Red, Green and Blue will have 1 place representation. Syntax: <style> input { background-color: #af0; } </style>
  • If it is 6 places then “#RRGGBB”.
  • Red, green and blue values will have 2 places. Syntax: <style> input { background-color: #dddddd; } </style>

RGB color code:

  • The colors are defined with “Red, Green and Blue” combination.
  • The method “rgb()” is used for RGB colors.
  • It takes 3 values “rgb(redValue, greenValue, blueValue)”
  • The value range for red, green and blue will be between 0 to 255. Syntax: rgb(0,0,255) blue color rgb(255,0,0) Red color

Ex:
<style>
input {
background-color:rgb(205,123,215);
}
</style>

RGBA (Red, Green, Blue, Alpha)

  • Alpha is for opaque 1.0 is full opaque
  • Range between 0.0 to 1.0 <style> input { background-color:rgba(255, 0, 0, 0.3); } </style>

CSS Units:

  • Units define size and position.
  • You can configure size with: height and width.
  • You can configure position with: x-axis, y-axis and z-axis.
  • The CSS units are categorized into 2 groups. -- Absolute Length Units -- Relative Length Units

Absolute Length Units :-

  • They are not relative to anything else and are generally considered as normal units.
  • These are not affected by other relative elements and their units.

Image description

Relative length units:
Relative length units:

  • These are related to other contents in the page.
  • The size of any element can be determined based on its parent, child or adjacent.
  • The advantages are when parent element size is changed will relatively affects the child element also.

em -- It uses the font size of parentelement and applies to current element.
ex -- X- height of elements’ font [width]
ch -- Defined for width, with regard to the root element.
rem -- Font size to the root element size.
ln -- Line height of the element.
vw -- 1% of the viewport’s width.
vh -- 1% of the viewport’s height.
vmin -- 1% of the viewport’s smaller dimension.
vmax --1% of the viewport’s larger dimension.

Cascading Rules:

  • If a set of effects are re-defined for same element with same type of selector then according to CSS rule the last set of effects are applied to element.
  • If element have to choose between type selector and class selector then it will always choose the "class selector".
  • If element is configured with both ID and class selector then always ID selector related effects are applied to element.
  • If different style attributes are defined in ID, Class and Type selectors and applied to any specific element. Then then all styles are applied to element. Only same name style attributes are overridden.

CSS 2D Transforms:

  • CSS 2D Transform feature allows the element to be transformed in 2-Dimensional space.
  • 2D is along X-Axis and Y-Axis.
  • CSS provides “transform” property to defined transformations.
  • CSS transforms are not supported on various browsers.
  • You have to use special plug-in for different browsers.

Various transforms provided by CSS are:
translate()-

  • It is used to move the element from its current position to a new position along x and y axis. Syntax: transform:translate(xPixels, yPixels); transform:translateX(pixels); transform:translateY(pixels); Note: Transformation happens in just one second, you can set timing for transformation by using "transition" attribute.

scale():

  • It is used to increase or decrease the size of element along x and y axis.
  • You can control the height and width of element. Syntax: transform:scale(scaleX, scaleY); transform:scaleX() transform:scaleY()
  • Scale units are defined in fractions -- 1 = 100 -- 1.5 = 150 -- 2 = 200 Syntax: transform:scale(2) // both x and y will be 200 transform:scale(2,1) // x will be 200 and y 100 transform:scaleX(2) // x will be 200 X = width Y = height

Skew():

  • Skew is used to tilt the image by specified angle. Syntax: transform:skew(sx, sy) transform:skewX(angle) transform:skewY(angle)

angle clockwise: 0 to 360
angle counter clockwise: -360

Rotate():

  • It rotates the element around its origin.
  • It uses value defined in deg.
  • It uses 0 to 360 deg angle
  • You can use -ve value for counter clockwise. Syntax: transform:rotate(‘angle’); transform:rotateX() transform:rotateY()

Transform Matrix:
-- Matrix allows to define all 2D transforms to single element.
-- The transform methods
-- translate(x,y)
-- translateX()
-- translateY()
-- scale(x,y)
-- scaleX()
-- scaleY()
-- rotate()
-- rotateX()
-- rotateY()
-- skew()
-- skewX()
-- skewY()
Syntax:
matrix(scaleX(), skewY(), skewX(), scaleY(),
translateX(), translateY())

CSS 3D Transforms:

  • CSS 3D transforms allows 3-Dimensional design.
  • It will have configuration for X, Y and Z axis.
  • The methods used for 3D are same as 2D but comprises of 3rd Dimension.

Translate3d():

  • It sets the position of element along x, y and z axis. Syntax: translate3d(tx, ty, tz)

Scale3d:

  • It changes the image size in 3 dimensions. Syntax: scale3d(x, y, z)

CSS Text Styling:
Font Styling :-
-It provides a set of attributes and values that are used to
format the text.
color -- Defines the foreground color.
font-family -- It defines the font family name like: Arial
font-size -- It defines the text size.
font-weight -- Defines normal, bold, lighter, bolder.
font-style -- Defines italic effect.
text-transform -- Defines uppercase, lowercase, capitalize, full-width. [affects the font size]
text-decoration -- Defines underline, overline, line- through.
-It is short had for various text decoration options like style of line, color of line etc.
-- text-decoration-color
-- text-decoration-style
-- text-decoration-line
text-shadow -- It defines a shadow for text.
text-align -- Left, center, right and justify
line-height -- Space between lines.
letter-spacing -- Space between letters.
word-spacing -- Space between words.
font-variant -- Caps, lowercase. [Without effecting the height of text it will change to caps]
text-indent -- First line spacing.
text-overflow -- Control the wrapping of text.
white-space -- Control the blank space.
direction -- Text direction
text-orientation -- Changes the orientation of text.

Ex: Font, Font Style, Color, Text Decoration

<!DOCTYPE html>
<html>
<head>
<title>Text Effects</title>
<style>
div{
color:red;
font-family: Arial;
font-size: 4em;
font-weight: bold;
font-style: italic;
text-transform: uppercase;
text-decoration: underline;
text-decoration-color: blue;
text-decoration-style: wavy;
}
</style>
</head>
<body>
<div>sample text</div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS Box Model:

  • Everything in CSS has a box around it.
  • Understanding boxes is important for designing layout.
  • It is often called as “Box Model”.
  • Box model comprises of Content Box -- The area where your content is displayed. It can be defined by using "height and width" attributes.

Padding Box -- The padding is around the content as white space. Its size can be controlled by using "padding".

Border Box -- The border box warps around the content or padding. It is controlled by using "border" property.

Margin Box -- The margin is the outmost layer wrapping the content, padding and border. It configures a white space around border. It is defined by using “margin”.

Image description

Set Margins, Padding and Border:
Margin
-- It specifies the space around border.
-- You define by using following properties.
-- margin [short hand – sets in all directions].
-- margin-top.
-- margin-bottom.
-- margin-left.
-- margin-right.

Padding
-- It specifies the space around content.
-- You can define
-- Padding-left.
-- Padding-right.
-- Padding-top.
-- Padding-bottom.
-- Padding. (All options are similar like margin)

CSS Transition:

  • CSS transition is a module of CSS.
  • Transition is used for configuring animation for initial and final state.
  • Initial state is before transformation.
  • Final State is after transformation. -You can control the behaviour using various CSS effects

-- timing
-- duration
-- other attributes

  • CSS Transition comprises of following properties

-- transition
-- transition-delay
-- transition-duration
-- transition-property
-- transition-timing-function

  • transition-delay : Delay is time taken to start animation.
    Syntax:
    transition-delay: 2s;

  • transition-duration : Time take to complete the transformation.Specifies the duration from initial to final and vice versa.
    Syntax:
    transition-duration: 5s;

  • transition-property : You can define several effects for transformation.
    -All effects are transformed from initial to final.
    -You can define only the effect that you want to transform by using transform-property.
    Syntax:
    transition-property: width,
    height;
    transition-property:all;

  • transition-timing-function : CSS provides a set of pre-defined animations functions which you can apply to content.
    -These effects have pre-defined timings and behaviour.
    -The transition timing functions are

  • linear: speed will be even from begin to end.

  • ease-in: starts slowly and increases towards end.

  • ease-out: starts quickly and slow down.

  • ease-in-out

  • steps

  • jump-start

  • jump-end

  • jump-none

  • jump-both

  • start

  • end

  • step-start

  • step-end

CSS Animations:
-- CSS animations are used to animate CSS transitions.
-- You can reduce the use of JavaScript and Flash for animation.
-- Animation can easily run on low bandwidth devices like mobiles, tabs.
-- Animation will work even when JavaScript is disabled or flash plugin is not available.
-- To create CSS animation, we need
-- @keyframes
-- animation
-- animation-name
-- animation-duration
-- animation-timing-function
-- animation-delay
-- animation-iteration-count
-- animation-direction
-- animation-fill-mode
-- animation-play-state

@Keyframes:

  • It is used to configure every frame in animation.
  • At each frame we can define effects for object.
  • Keyframes are defines with initial, final, and intermediate steps.

Syntax:

@keyframes identifierName
{
from { effects for initial state }
to { effects for final state }
}

Enter fullscreen mode Exit fullscreen mode
  • Keyframes are applied to any element by using "animation-name" property Syntax: P { animation-name: keyframeIdentifierName; }
  • You can control the iteration count, the number of times to display by using "animation-iteration-count"
  • You can control animation direction by using "animation-direction"

CSS Position:

  • Generally, elements are placed according to the document layout flow.
  • Position allows to make element behave differently and take them out of the document flow.
  • CSS Positions are defined by using “position” style attribute.

Static Position:

  • It is according to the normal flow of document.
  • It is the default position for every element.
  • It will not have any effect on the element position.
  • Static position is not affected by top, right, bottom, left and z-index attributes. Ex: p { position: static; right: 10px; }

Sticky Position:

  • Element is positioned according to the normal flow of document.
  • It can make the content sticky after scrolling to the specified margin.
  • It required the margins to define and position by using left, right, top or bottom.

Fixed Position:

  • The element is removed from normal document flow.
  • Element is no longer a part of DOM flow.
  • Its position is fixed with left, right, top and bottom attributes.
  • It will not move from the position defined.
  • It locks the component at fixed position on page.

Relative Position:

  • It according to the normal document flow.
  • Its position will be relative to adjacent or parent element.
  • It is from the parent or from adjacent.

Position Absolute:

  • The element is removed from the normal document flow.
  • It is positioned relative to its closest element.
  • It is affected by using left, right, top and bottom values.

As you apply these techniques, your CSS skills will continue to grow, opening doors to endless design possibilities.

Thank you for taking the time to read this article. I hope it has helped you on your CSS journey!

Top comments (0)