Learn CSS

2020-01-05 Moduatecss

HTML defines the structure of web page content, whereas CSS styles the structure and makes it look beautiful.

CSS is super easy to learn. We will start by drawing a basic wireframe, which we can then reference when styling our page. Feel free to follow along with a pen and paper.

Scope (Requirements)

We want a header on our webpage, with the header containing our logo on the left hand side and a navigation bar containing links on the right hand side.

The main content will go below the header, centered horizontally on the page. This section will contain a heading, an image and some text.

Below the main content and at the bottom of the page is where we will place our footer, which will contain a copyright notice.

basic layout

So in HTML each of these boxes will act as containers, for us to place related content.

When designing your website layout it can be helpful to think of everything on the page as belonging to a grid, with this grid consisting of rows and columns.

The HTML tags used for this layout will be as follows:

  1. <header>

    • have a blue background
    • span the full width of the page
    • have a height of 75 pixels
    • All text within the header will be colored white and centered vertically

    This tag will contain two direct children:

    • <div> containing our logo
    • <nav> tag for our navigation
  2. <main>

    • content section will be constructed with the html main tag,
    • fixed width of 700 pixels
    • top and bottom margins of 50 pixels
    • centered horizontally on the page.

    This tag will contain three direct child tags:

    • <header> tag containing our posts title (with text centered horizontally)
    • <div> containing our image
    • <div> containing our posts text (text size and line height will be slightly larger than the default to increase readability)
  3. <footer>

    • custom grey background color
    • span the full width of the page (to match our header)
    • height of 100 pixels
    • nested text will be colored white
    • text will be centered both vertically and horizontally

    As mentioned before the footer will contain our copyright text

Our wireframe as a result from the above requirements:

wireframe

Create a new text document and save it as index.html, as this is typically the name given to the homepage of a website.

Note: the correct file extension of .html is important.

Also, if you don’t have an image stored locally on your computer, we recommend downloading one from the internet and storing it in the same directory as your newly created index.hml file, as we will be using this image later in the tutorial.

html and image files in same directory

I’m going to use Atom in this tutorial, but any text editor will do.

Lets Setup Our HTML

So lets add our <html>, <head> and <title> tags, nesting the text Our Website between our open and closing <title> tags.

<html>
  <head>
    <!-- This is how you write comments in HTML -->
    <title>Our Website</title>
  </head>
</html>

Next add the <body> tags with the <header>, <main> and <footer> tags nested within.

<html>
  ...
  <body>
    <header></header>
    <main></main>
    <footer></footer>
  </body>
</html>

Between the open and closing <header> tags, add child <div> and <nav> tags.

  1. In the headers > div tag add an <a> (anchor) tag.

    • Add an id attribute with a value of logo
    • Add a href attribute with a / (forward slash) as it’s value (this lets us redirect back to our home page, when our logo is clicked).
    • Set the anchor tags inner text to be Our Website.
  2. Now jump to the headers > nav tag and add an <ul> (unordered list) with three <li> (list item) elements, as children. Inbetween each <li> open and closing tags:

    • Add an <a> tag and leave the href attribute value empty (as we currently don’t want these links going anywhere).
    • Set the inner text of these anchors to be one of About, Blog or Contact.
<html>
  ...
  <body>
    <header>
      <div>
        <a href='/' id='logo'>Our Website</a>
      </div>
      <nav>
        <ul>
          <li>
            <a href=''>About</a>
          </li>
          <li>
            <a href=''>Blog</a>
          </li>
          <li>
            <a href=''>Contact</a>
          </li>
        </ul>
      </nav>
    </header>
    ...
  </body>
</html>

Hop into the <main> tag and add one <header> and two <div> tags

  1. In the main > header tag add an <h1> tag with contents of “First Blog Post”.
  2. In the first main > div tag add an <image> tag and set its source to the image we stored in the same directory as our index.html earlier.
  3. In the second main > div tag, add three paragraph tags. Our paragraph tags will contain lorem ipsum placeholder text.
<html>
  ...
  <body>
    ...
    <main>
      <header>
        <h1>First Blog Post</h1>
      </header>
      <div id='main-image'>
        <img src='image.jpg' alt='building' width='700px' />
      </div>
      <div>
        <p>Lorem ipsum ...</p>
        <p>Sed ut perspiciatis ...</p>
        <p>At vero eos et  ...</p>
      </div>
    </main>
    ...
  </body>
</html>

In our <footer> tag add a child <div>. Inside this child div add the HTML entity for the copyright symbol © followed by the year and your name, like so:

<html>
  ...
  <body>
    ...
    <footer>
      <div>&copy; 2019 Moduate</div>
    </footer>
  </body>
</html>

Note:

  • An HTML entity is a piece of text that begins with an ampersand (&) and ends with a semicolon (;)
  • The html entity &copy; will be displayed as © in your browser.

Notice how all these tags correspond to the ones we wire-framed earlier.

Let’s save our file ctrl + s and open it up in our browser. As you can see, although all of our content is displayed, it still needs styling (as we haven’t yet added our css).

Create a new file and save it as style.css. Make sure to put this file in the same directory as your index.html and image files.

css, html and image files in same directory

We now need to define a relationship between our html and css files. This is achieved with the <link> tag, which gets nested in the <head> tag.

Notice here that we said head and not header (careful not to mix those up).

Setup the <link> tag as follows:

  • Define the relationship by adding a rel attribute and set its value to stylesheet.
  • Add a type attribute with a value of text/css
  • Add a href attribute with a value of style.css (our css file URL - can be absolute or relative).
<html>
  <head>
    ...
    <link rel='stylesheet' type='text/css' href='style.css' />
  </head>
  ...
</html>

Note:

  • <link /> tags are self closing
  • We were able to use a relative path here as the href value, because our html and css files are in the same directory.

This is what our site should look like (without any styling):

site with no css (no styling)

The complete html file can be found at the end of this tutorial.

Time To Add Our CSS

So with CSS, first you select an element that you want to style. So if you want to style the html <header> element, for example. Your selector would be header (the elements name), followed by opening and closing curly brackets.

header {
  /* This is how you write comments in CSS */
}

Everything inside these curly brackets, also known as the declaration block, would then be applied to all <header> tags on the page.

header

So remember that we wanted the header to have:

  • a background color of blue
  • a height of 70 pixels

So lets add the height property and set its value to be 70px and also add the background-color property with the following hex value #4267b2

Note: Hex values start with a hash. Also, we used a hex value here instead of just using blue as the value, because we wanted a custom shade of blue.

header {
  height: 70px;
  background-color: #4267b2;
}

If we save our css file and refresh the browser, we can see that our header style was applied twice.

First time was to the pages first header element (containing our logo & nav), and the second was to our blog post header element (within the main tag).

Lets give our top most header element an id of pageHeader.

<html>
  ...
  <body>
    <header id='pageHeader'>
      <div>
      	...
      </div>
      <nav>
      	...
      </nav>
    </header>
  	...
  </body>
</html>

Now lets update our css header selector to match our elements id value of pageHeader.

Note:

  • id selectors start with a hash (#anIdSelector),
  • class selectors start with a period (.aClassSelector).
#pageHeader {
  height: 70px;
  background-color: #4267b2;
}

Notice now after saving our css file and refreshing the browser, that only the first header element (with our pageHeader id) has a blue background.

The elements containing text within our #pageHeader are currently displayed on their own lines.

However, our scope required that they all be displayed on the same line.

To do this we need to change several display property values (for several elements that have a default value of block), to instead have a value of inline-block.

We will need to change this value for our:

  • logo id
  • nav element
  • list item elements

So lets select our #logo, nav and li elements, by comma separating the selectors and making use of a single declaration block.

#logo, nav, li {
  display: inline-block;
}

Now position the nav element 0 (zero) pixels to the right.

Note: When using a value of 0, the unit of measurement is not required, as 0 will always be 0.

nav {
  position: absolute;
  right: 0;
}

When viewing in the browser, we can see that our navigation list doesn’t seem to be positioned in the right place.

This is because both our <body> and <ul> html tags have preset default margins.

So lets clear all default margins and padding, from all elements on our page, by using the wildcard selector, at the top of our css file.

* {
  margin: 0;
  padding: 0;
}

Lets go back into our index.html file and wrap our #pageHeader child elements (the <div> and <nav> elements), with a new <div> element (we are creating a new container for these child elements).

<html>
  ...
  <body>
    <header id='pageHeader'>
      <div>
        <div>
        	...
        </div>
        <nav>
        	...
        </nav>
      </div>
    </header>
  	...
  </body>
</html>

We can now select this new container (div) in our style.css using the css child combinator (>).

#pageHeader > div {
  height: 100%;
  display: flex;
  align-items: center;
  position: relative;
  margin: 0 25px;
}

Here we are setting the height to be 100% of its parent (in this case 70px).

A display of flex allows us to align our items vertically (centered vertically).

The position: relative; css used here, changes our <nav> element to set its absolute position, relative to our #pageHeader > div element.

The margin property leaves the top & bottom at 0 and changes the left & right margin values to 25 pixels.

Lets now select the anchor element and within its declaration block set the text decoration to none & color to white.

a {
  text-decoration: none;
  color: white;
}

This removes the underline from your hyperlinks and changes the font color to white.

Lets save our file and refresh the browser.

Notice that our #logo font size is a little bit too small. So lets fix that.

#logo {
  font-size: 2em;
  font-weight: bold;
  font-family: Ubuntu, sans-serif;
}

We have styled the #logo (element with an id of logo) by increasing both the font size & font weight and by adding additional fonts to the font family property. Basically the browser will select the first font available to our machine from the comma separated list of fonts that we have provided.

The last element we will select and style in our first <header> element, are the list item tags. So lets do that.

li {
  margin-left: 25px;
  font-size: 1.2em;
  font-family: Ubuntu, sans-serif;
}

footer

Before styling the main content of our page, first we will style our <footer>.

footer {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-family: Ubuntu, sans-serif;
  background-color: #2D2D2A;
}

Our footer element has a height of 100 pixels.

The display properties flex value here, allows us to both vertically and horizontally center our child elements with the justify-content and align-items properties.

We are also setting the footers background color to a hex value (#2D2D2A).

main

The last section in our html page that needs styling is the <main> element.

main {
  width: 700px;
  margin: 50px auto;
}

h1 {
  text-align: center;
  font-family: Ubuntu, sans-serif;
}

#main-image {
  margin: 12px auto;
}

p {
  font-size: 1.2em;
  line-height: 1.4em;
  font-family: Ubuntu, sans-serif;
}

We are setting a width of 700 pixels for the main element.

A margin of 50 pixels for the top and bottom, with a value of auto for the left and right (this will center it horizontally).

We are horizontally centering our h1 text and specifying which font we want used.

The #main-image id selector is used here to select our image, setting its top & bottom margins to 12 pixels, with the left & right set to auto.

Lastly, our <p> (paragraph) element has its font-size and line-height increased from the default sizing. We are also specifying what font we want used (if the font is available on a users machine) in order of precedence (left values have higher priority over right values).

This is what our site should now look like, after adding css:

site styled with css

Our files should now look like this:

index.html

<html>
  <head>
    <title>Our Website</title>
    <!-- <link rel='stylesheet' type='text/css' href='style.css' /> -->
  </head>
  <body>
    <header id="pageHeader">
      <div>
        <div>
          <a href='/' id='logo'>Our Website</a>
        </div>
        <nav>
          <ul>
            <li>
              <a href=''>About</a>
            </li>
            <li>
              <a href=''>Blog</a>
            </li>
            <li>
              <a href=''>Contact</a>
            </li>
          </ul>
        </nav>
      </div>
    </header>
  	<main>
      <header>
        <h1>First Blog Post</h1>
      </header>
      <div id='main-image'>
        <img src='image.jpg' alt='girl with grapes' width='700px' />
      </div>
      <div>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>
        <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p>
      </div>
  	</main>
  	<footer>
  		<div>
  			&copy; 2019 Moduate
  		</div>
  	</footer>
  </body>
</html>

style.css

* {
  margin: 0;
  padding: 0;
}

#pageHeader {
  height: 70px;
  background-color: #4267b2
}

#pageHeader > div {
  height: 100%;
  display: flex;
  align-items: center;
  position: relative;
  margin: 0 25px;
}

#logo, nav, li {
  display: inline-block;
}

nav {
  position: absolute;
  right: 0;
}

#logo {
  font-size: 2em;
  font-weight: bold;
  font-family: Ubuntu, sans-serif;
}

li {
  margin-left: 25px;
  font-size: 1.2em;
  font-family: Ubuntu, sans-serif;
}

a {
  text-decoration: none;
  color: white;
}

main {
  width: 700px;
  margin: 50px auto;
}

h1 {
  text-align: center;
  font-family: Ubuntu, sans-serif;
}

#main-image {
  margin: 12px auto;
}

p {
  font-size: 1.2em;
  line-height: 1.4em;
  font-family: Ubuntu, sans-serif;
}

footer {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-family: Ubuntu, sans-serif;
  background-color: #2D2D2A;
}

Conclusion

  1. First you select what you want to style with a css selector.
  2. Then you declare what styles you want to apply in the declaration block.
/* tag selector */
a {

}

/* id selector */
#logo {

}

/* class selector */
.title {

}

Its a good idea to indent for easy readability, with each rule ending with a semi colon and each rule being written on a new line.

/* Multiple selectors can be comma separated */
a, #logo, .title {
  color: white;
  font-weight: bold;
}

/* Select any elements with the title class that is inside a div element */
div .title {
  font-size: 2em;
}

/* Matches any element with the title class that is a direct descendant (child) of a div tag */
div > .title {
  font-style: italic;
}
  • Selecting multiple elements is achieved by comma separating them.
  • The space combinator () selects nodes that are descendants of the first element.
  • The child combinator (>) selects nodes that are direct children of the first element.

There are three places to put your CSS:

  1. Written in a separate css file with a file extension of .css (what we did in this tutorial).
  2. Written in-between an open and closing <style> tag (within the <head> tag).
<html>
  <head>
    ...
    <style>
      a, #logo, .title {
      	color: white;
      	font-weight: bold;
      }
      div .title {
      	font-size: 2em;
      }
      ...
    </style>
    ...
  </head>
  ...
</html>
  1. Written inline (inside of an HTML tag).
<html>
  ...
  <body>
  	...
  	<nav style='position: absolute; right: 0;'>
      ...
  	</nav>
  	...
  </body>
</html>
Loading...
Moduate - Videos and Blog Posts for Developers

Moduate makes videos and posts blog articles for developers.

Helping developers be more productive since 2018!