DEV Community

loading...
Cover image for CSS - Diving inside the basics.

CSS - Diving inside the basics.

rishiabee profile image Rishi Updated on ・9 min read

What is CSS?
It makes the wepage look good.
HTML is the structure the of a webpage.
CSS allows you to style the HTML page.

For any webpage, HTML is required. CSS is optional.

What does CSS mean?
Cascading Style Sheets.



How to make use of CSS?

There are 3 ways of using CSS in an HTML file.

  1. Inline Styling
  2. Style Tag
  3. Using an external Style Sheet

1. Inline Styling

An HTML element consists of an HTML tag eg: <div></div>.

Most tags have one or more attributes.

Inline Styling adds a style attribute to an html element.

To style an html element h1 with a background property with a value of red :
we add the attribute style="background: red" , which is also known as a CSS declaration.

      <h1 style="background: red">Hello Inline Styling</h1>

Therefore, a CSS declaration consists of a property and a value.

The values are tightly coupled to a specific property.
These values can be categories as:

  • Predefined Options
  • Colors
  • Length, Sizes & Numbers
  • Fucntions

Inline styling is very easy to write but not recomended in the long run.
As the html code gets bigger, it becomes harder to maintain.

2. Style Tag

It is a normal html tag <style></style .
Style Tag is added in the <head></head> section of the html file.

Within the style tag, we add CSS rules.
A CSS rule consists of at least one selector and one or more css declarations.
The selector indicates which html element(s) we are targeting and what style(s) to apply.
Within that selector, we add in the CSS declaration(s) we want.

<style>
    p {
      background: yellow;
    }
</style>

The above CSS rule will tell the browser to look within the html file for all p elements and apply the defined css rule, which in this example, the rule is: to apply a ==yellow== background to all p elements.

A "rule" in CSS is a combination of at least one selector (WHAT TO STYLE) and at least one css declaration (HOW TO STYLE IT).

3. Using an External Style Sheet.

For Inline Styling and Style Tag, the css delcarations & css rules exist within the same html file.

External Style Sheet, as the name implies, the css file resides externally from the html file.

We start by creating a new file with the extension of .cssexample myStyle.css.
Then, within the html we specify that we want to use that external style sheet.
To do so, in the <head></head> section of the html , we add a <link> element.

<link rel="" href="">

We assign the attribute rel with the value of stylesheet.
And for the href attribute we indicate where our myStyle.css is located.

 <link rel="stylesheet" href="myStyle.css">

Inside the myStyle.css we use CSS rule(s) to style our html elements.

span {
  background: pink;
}

This css rule applies a pink background to all p elements.

Advantages of using an external Style Sheet:

  • Can use multiple external style sheets to better organise the way we style our HTML document.
  • Browsers normally cache the external style sheets, so subsequent page loading are faster.



Selectors, Properties & Values

A CSS rule consists of at least one selector and one or more css declarations.
There are different types of selectors to make it easier to target differnt HTML elements.
Namely:

  • Element selectors
  • Class selectors
  • Universal selector
  • Id selector
  • Attribute selector

Element selectors

A HTML document consists of multiple HTML elements.
Inside an HTML file we have

  • Head element <head></head>.
  • Body element <body></body>.
  • Div element <div></div>.
  • Paragraph element <p></p>.
  • and many more...

Element selectors apply the same style to all the same elements.

    p {
      background: yellow;
    }

This will apply a yellow brackground to all the p elements.

Class selectors

With the introduction of CSS, all HTML elements were given the class attribute. This was to help with css styling.

Class selectors applies the same style to all the elements having a class with the same value aka class name.

A class is added to the html tag by using the class attribute.

      <div class="iAmAClassSelector">
        Sesame snaps dragée gummies fruitcake carrot cake cookie cake macaroon. Jujubes chupa chups marshmallow pudding. Wafer gingerbread chocolate cake cupcake. Muffin tiramisu muffin muffin icing chocolate bar chocolate cake soufflé carrot cake.
      </div>

A class selector starts with a . followed by the class name.

.iAmAClassSelector {
  background: aquamarine;
}

We can define multiple class selectors and use them simultaneously.

.iAmAClassSelector {
  background: aquamarine;
}

.iAmAnotherClassSelector {
  color: orange;
  font-size:14px
}
      <div class="iAmAClassSelector iAmAnotherClassSelector">
        Sweet roll apple pie lollipop lemon drops. Pastry fruitcake halvah oat cake wafer dragée.
      </div>

Universal selector

A Universal selector applies a set of styles to all the elements in the page. ==rarely used==
It starts with an * followed by the css rule(s).

* {
  color: brown;
}

The above sets all the text color to brown, within the html page.

Id selectors

An id selector, applies a set of CSS rules to one html element having that particular id.
NOTE: Anid should be unique in an html file.

<div id="idSelector">
Cupcake lemon drops bonbon. Cake dessert sesame snaps candy gingerbread jelly donut pudding biscuit. Biscuit brownie donut marshmallow chocolate bar jelly beans macaroon. Carrot cake dragée lemon drops pudding candy canes. Danish soufflé jujubes bear claw ice cream gingerbread jelly beans topping.
</div>

In the CSS stylesheet, an id selector starts with a # followed by the the identifier.

#idSelector {
  font-size: 20px;
}

Attribute selectors

All HTML elements can have attributes which provide additional features to the element.
Attributes are defined as name/value pairs like: name="value" but some can only have a name.

  <button disabled>Click me</button>

In the CSS stylesheet, an attribute selector is enclosed withing square backets [ ].

[disabled] {
  color: grey;
  font-size: 20px;
}

Styles Orders & Priorities

As we have seen so far, we can define multiple CSS rules using multiple type of selectors.
It is good to note, as we keep defining more and more CSS rules to enhance our HTML look and feel, each rules will have different priorities based on:

  • how they are applied
  • their order

If we apply two CSS classes to the same element and both preform the same type of styling, the styling declared in the class at the last (at the bottom most) will be the one taking effect.

.redText {
  color:red;
}

.greenText {
  color:green;
}
<div class="redText greenText">What color am I ?</div>

In the screenshot below we can see that the broswer has crossed out the CSS rule of the .redText class and prioritised the one of the .greenText class.

If we have an id selector and a class selector targeting the same html element. The CSS rules defined in by the id selector takes predecence over the class selector.

#aquamarine {
  background: aquamarine;
}

.red {
  background:red;
}
<div  id="aquamarine" class="red">What color is my background ?</div>

In the screenshot below we can see that the broswer has crossed out the CSS rules of the.red class selector prioritised the one of the #aquamarine attribute selector.

Now, if we have an inline styling, a CSS rule with id selector and a CSS rule withclass selectors.
The order of precedence is:

  • first: inline styling
  • second: id selector
  • third: class selector
#aquamarine {
  background: aquamarine;
}

.red {
  background:red;
}

.green {
  background:green;
}
<div style="background: pink" id="aquamarine" class="red green">What color is my background ?</div>

In the screenshot below we can see that the broswer has crossed out all CSS rule, except for the element.style which is the inline styling.

CSS means
: Cascading Style Sheet.

Cascading means
: The styles (css rules) can fall (or cascade) from one style sheet to another.

Therefore, to avoid conflicts from multiple rules overlapping, the browser assign each stype of selector a specificity .

Order of Specificity

Specificity Selector Type
Highest Inline Styles
Higher #ID selectors
High .class , :pseudo-class and [attribute] selectors
Low <tag> and ::pseudo-element selectors

If two or more rules target the same element and set different styles for the same property, this conflict needs to be resolved.

Specificity is all about resolving conflicts that arise from multiple CSS rules, which target the same element.

Inheritance

In an html document, html elements are often nested one inside another.

For example below, the div div elements are nested withing thebody element.
And each of the three div elements have different child elements.

<body>
    <div>
        <p>Hello 1</p>
    </div>
    <div>
        <span>Hello 2</span>
    </div>
    <div>
        <div>Hello 3</div>
    </div>
</body>

The child element (the one nested inside the parent element), inherits the styles applied to the parent element. However, the order of specificity/priority still applies and any styling applied to the child element will take precedence over the parent's styling.

In this example below, the div elements are nested inside of a body .
All child elements will inherit the font-size: 20px and background: gold styling.
However, some child div elements have the value of the property background reassigned.

body {
  font-size: 20px;
  background: gold;
}
#aquamarine {
  background: aquamarine;
}
.red {
  background:red;
}
<div  id="aquamarine" class="red">What color is my background ?</div>



Combinators

Combinators make it easy to target specific html elements by combining two or more selectors.

Selecting only elements having .red class.

.red {
  color: red;
}

Selecting only div elements having a nested p element.

div p{
  background: yellow;
}

Selecting onlydiv elements having a nested p element specfically with a .red class.

div p.red{
  font-size: 30px;
}
<div class="red">Cupcake lemon drops bonbon.</div>
<div>Lungo percolator, single origin so milk rich, breve rich body mocha a extra.</div>
<div><p> Biscuit brownie donut marshmallow chocolate bar jelly beans macaroon.</p></div>
<div>
  <p class="red">Cup, irish arabica, flavour body redeye doppio extra single shot espresso. </p>
</div>

Types of Combinators

There are 4 types of combinators:

  1. Adjacent Sibling Selector. Combined by a + sign. div + p { }
  2. General Sibiling Selector. Combined by a ~ sign. div ~ p { }
  3. Child Selector. Combined by a > sign. div > p { }
  4. Descendant Selector. Combined by a *a white space *. div p { }

A combinator is a CSS feature which allows you to combine two selectors in a dependent way.

Combinators (~, +, >) tie two selectors together.

Adjacent Sibling Combinator Selector

Combined by a + sign.

The Adjacent Sibling Combinator Selector assigns a style only to the second element directly after the first element.

❕ Note:
: The sibblings must share the same parent.
: The second element must come immediately after the first element.

h1 + div {
  color: red;
}

h2 + h3 {
  color: blue;
}
<div>
  <h1>1. No CSS applied</h1>
  <div>2. Adjacent Sibling</div>
  <h2>3. No CSS applied</h2>
  <h3>4. Adjacent Sibling</h3>
  <div>5. No CSS applied</div>
  <div>6. No CSS applied</div>
  <h1>7. No CSS applied</h1>
  <div>8. Adjacent Sibling</div>
</div>

General Sibiling Combinator Selector

Combined by a ~ sign.

The General Sibiling Combinator Selector assigns a style to any sibiling element placed after the first element.

❕ Note:
: The sibblings must share the same parent.
: The second element must come after the first element, not necessarily immediately after.

h1 ~ div {
  color: red;
}

h3 ~ div{
  color: blue;
}
<div>
  <h1>1. No CSS applied</h1>
  <div>2. General Sibling</div>
  <h2>3. No CSS applied</h2>
  <div>4. General Sibling</div>
  <h3>5. No CSS applied</h3>
  <div>6. General Sibling</div>
  <div>7. General Sibling</div>
  <h1>8. No CSS applied</h1>
  <div>9. General Sibling</div>
</div>

Child Combinator Selector

Combined by a > sign.

The Child Combinator Selector assigns a style to any child element placed directly under the parent element.

❕ Note:
: Second element must be a direct child of the first element.

section > div {
  color: red;
}

span > div {
  color: blue;
}
<section>
  <h1>1. No CSS applied</h1>
  <div>2. Child Selector</div>
  <h2>3. No CSS applied</h2>
  <div>4. Child Selector</div>
  <h3>5. No CSS applied</h3>
  <div>6. Child Selector</div>
  <article>
      <div>7.1 No CSS applied</div>
  </article>
  <span>
      <div>7.2 Child Selector</div>
  </span>
  <h1>8. No CSS applied</h1>
  <div>9. Child Selector</div>
</section>

Descendant Combinator Selector

The Descendant Combinator Selector assigns a style to any child element placed anyware under the parent element.

❕ Note:
: The second element must be a descendant of the first element, not necessarily direct descendant.

section div {
  color: red;
}
<section>
  <h1>1. No CSS applied</h1>
  <div>2. Descendant Selector</div>
  <h2>3. No CSS applied</h2>
  <div>4. Descendant Selector</div>
  <h3>5. No CSS applied</h3>
  <div>6. Descendant Selector</div>
  <article>
      <div>7.1 Descendant Selector</div>
  </article>
  <span>
      <div>7.2 Descendant Selector</div>
  </span>
  <h1>8. No CSS applied</h1>
  <div>9. Descendant Selector</div>
</section>

Further Reading:

Discussion (1)

pic
Editor guide
Collapse
iamdejean profile image
Jean Japheth Ezekiel

You did justice to CSS