Site preferences
Preferences



*The preferences are saved using cookies because this website does not use Javascript.
To clear the cookies, select Clear Cookies and click submit, this will also reset all the preferences to default.
The cookies are not used for analytics, read the privacy policy for more details.

Writing a Website part 2: HTML and CSS

This post is for beginners who knows how to operate a computer, and wants an introductory course on web development.

This page was published on .
Tags:


This is part two of the series on writing a website, in the part one, Recipe for Making a Website, I wrote about what we can use to write a website, but not how to write one.

The images in here might be unreadable when reading on devices with small screen size. This is because the images are screenshots taken from a laptop screen and resized, I have provided sufficient (or I believe they are sufficient) descriptions for them. Ideally, you should be able to get the same results in your system if you do the steps I mention in this article. If you still need to see the images, please open them in a new tab.

A website is usually created to provide information to a visitor. Which is typically written in text format. There are many ways to send this information to the visitor, but let us not focus on that for now, what we need is to write that information down somehow so that it can be shared.

But wait, shouldn't we figure out how to share the information first so that we can write it down in a way that it can be shared?

It might seem like a chicken-and-egg problem, but fortunately for us, this is already solved. There is an existing and widely used protocol named HTTP (Hypertext Transfer Protocol) that supports transferring information through the internet, and that protocol supports a markup language called HTML, which is what we are going to use today.

HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content.

HTML is a complex and evolving markup language, but it is easy to use because there are very few rules you need to learn to write a full-fledged website.

Structuring the web page

In HTML, the structure is defined using tags, a tag in HTML is usually written in the format <tag-name> this is called an opening tag. An opened tag can be closed by writing the same tag and adding a / after < (e.g. </tag-name>).

An element, or to better word it, an HTML element, often consists of opening and closing tags. Everything in between those tags are called content of that element. For example, <q>flower</q> creates a quote element, and it is rendered as flower — here flower is the content.

You can place an element within another element, this is called nesting. But what we call it is not relevant, all you need to know is that you can infinitely nest elements! But be careful, the more nested the elements are, the more you burden the visitor's browser and their RAM, so we must try to reduce nesting as much as possible.

Some elements cannot have any child (nested) element or text contents, they are called void elements. Void elements only have a start tag; end tags must not be specified for void elements. An example of this is the <input> tag.

Some HTML formatting tools (like prettier) try to self-close void tags by inserting a trailing / after the tag name (<input/>), there are some historical reasons for that, like supporting XML parsers where there are no concepts of void tags.

Fun fact, no browser will complain or behave weirdly if you self-close a void tag (citation needed). But self-closing is not a concept in HTML, so any tool trying to insert a self-closing tag in HTML to support XML parsers is fighting with two things that do not support each other.

Though no error will be thrown, there are some more restrictions on what elements can be placed in another, but let us not worry about that for now and learn different elements that we can use.

Scemantic elements

Most elements convey semantic meaning, and purpose. A <p> tag is used to create a paragraph element, for example. This paragraph is written in HTML, like this.

<p>
  Most elements convey semantic meaning, and purpose. A <code>&lt;p&gt;</code> tag is used to create a paragraph element, for example. This paragraph is written in HTML, like this.
</p>

Noticed the weird &lt;p&gt;? In HTML, if you want to write < or > as text, you need to escape them. This can be done by writing &lt; and &gt;. So &lt;p&gt; will create the text <p> instead of creating a tag. Modern IDEs will probably highlight them so that it will be easier to read.

There are many more characters that you can escape like this, you might be interested in reading about using character escapes in markup and CSS.

A good website with lots of content will have more paragraph elements than any other elements, but showing just plain text would be a bit boring and might not suit everyone's needs or taste. There are elements to style texts within a paragraph, and some of these do similar things, but you can use them based on their semantic meaning.

For example, both <i> and <em> tags are rendered (displayed) by the browser by making its content italic. Scemantically, <i> can be used to make a text italic in style, but to emphasize a text, we should use <em> tag instead.

Other similarly styled tags are <b> and <strong>, while both of them render the text in bold, <strong> tag is used to show strong text that has a strong importance. And <b> tag is for, as you guessed, to make the text bold (technically, increasing the font weight).

While paragraphs are important, it is also important to have heading and subheading for the document, this makes it easier for the reader to traverse through the document. <h1> tag is used to show the heading of the document, a document must have only one of them (though as usual, the browser won't stop you from having more).

You can create a subheading by increasing the number after the h in the heading tag, at present, it is possible to have subheadings from h2 to h6. When using them, one must not skip a heading level, i.e a h3 must not be created if there is no h2 tag present before it. The higher the number, the smaller the text, but as I already mentioned, it is used to write headings and subheadings, and not to style texts.

Writing an HTML document

Now that we learned how to create text content, let us focus on putting this into a document and see it from a browser.

As I mentioned at the beginning, the HTML is an evolving language, currently HTML5 is widely used, it has support for more semantic HTML elements than its prior versions. The browser must know the document format and version that we are using, this is done by using the <!DOCTYPE> declaration. Did you notice that I wrote declaration and not tag? This is because the declaration is not an HTML tag. It is information to the browser about what document type to expect.

Okay, now that we know what to do, let us create this document for real this time.

To create an HTML document, any text editing software can be used. BUT, we are going to write plain text here, so it is better if you don't use a word processor. Use a simple text editor, like ed, vi, vim, Emacs, Atom, Notepad++, or in worst-case use Sublime Text, or VS Code. But if you have opened Microsoft Word, close it, we don't need it here.

Create a new folder in your system — name it whatever you feel like, it is not relevant — now create an empty file within that folder named index.html, this time, the name is important, make sure you spelled it correctly.

The name index.html is usually looked up by most tools that can be used as a server (homework, find the historical reasoning behind it). Though we are not using any such tools at this point, we will need it in the future, so let us stick to that naming convention for now.

After creating the empty file, open it using your text editor and write the DOCTYPE to it. For HTML5, the DOCTYPE is written as <!DOCTYPE html> (yes it is not a typo it is html and not html5).

The HTML document has a few tags that need to be placed to be rendered properly. The first one is <html>, this is the root element of the HTML document, and there should be only one root element present in an HTML document.

Your file should now look like this:

<!DOCTYPE html>
<html>
</html>

Inside the <html> element, we can place two elements, one is <head> which can contain some additional information about the file, like the title of the document, information about the author, a brief description, how the document should be rendered, etc. For now, let us just add a title.

<!DOCTYPE html>
<html>
  <head>
    <title>A simple HTML document</title>
  </head>
</html>

Simple? I will add two more things.

To support more languages, we can tell the browser to use the UTF-8 character set when rendering the text by placing this meta tag within the head element: <meta charset="UTF-8">.

To tell what language the webpage is using to the browser, and any assistive technology the visitor uses, we can use the lang attribute in the html tag: <html lang="en-gb-oxendict">.

I am using the Oxford English Dictionary spelling (British English) here. To find the correct code for the language you are using, try the Language Subtag Lookup. You must do this because an empty lang tag means that the language is undefined.

The other element we can place inside the <html> is the <body> element, all contents that we write should be placed within the body.

<!DOCTYPE html>
<html lang="en-gb-oxendict">
  <head>
    <meta charset="UTF-8">
    <title>A simple HTML document</title>
  </head>
  <body>
  </body>
</html>

While we can place all the contents within the body, it is a good practice to further divide the sections. For someone using assistive technology, it would be nice to have indication of different sections of the page, we call them landmarks. We are not going to use them now, just keep it in your mind, by the end of this series you will learn when and how to use them.

What you have now created is called an HTML boilerplate, you can copy that file content and when creating more HTML files. Some IDEs (Integrated Development Environments) can generate this (and a bit more) for you, it is up-to you to figure that out.

Now that the boilerplate is ready, let us put some content in it after remembering the rules:

  • A document must have only one h1 tag.
  • Subheadings must not skip levels.
  • All paragraphs must use p tag.
  • Ensure that the document follows a semantic structure.
<!DOCTYPE html>
<html lang="en-gb-oxendict">
  <head>
    <meta charset="UTF-8">
    <title>A simple HTML document</title>
  </head>
  <body>
    <h1>Welcome to my simple HTML page</h1>
    <p>
      An HTML page is used for sharing information with others. And to ensure that <em>everyone</em> can access the page, we must be conscious of the <strong>semantic</strong> and <strong>accessibility</strong> when writing it.
    </p>
  </body>
</html>

Now save the file with the above content, once saved, you can open the index.html file using your web browser. There are many ways to do this, one way is to just drag the index.html file into the web browser. Or you might be able to right-click on the file and open it using the default browser (this flow varies between OS and Desktop environments).

Once you have opened the file in the browser, you might see something like this screenshot.

Firefox screenshot

Firefox tab with A simple HTML document as title. The webpage contains black text in white background. The heading says Welcome to my simple HTML page, and it is rendered as a big and heavy text.

The paragraph below the heading has the text everyone rendered in italic style. The texts semantic and accessibility are rendered in bold letteres.

Styling the web page

That screenshot above was very plain looking, and if you are reading my website in one of its dark themes, you might have strained your eyes, so how about we make it a bit better?

Unlike the structure of the website, styling is not a compulsory thing to do. But just like the structure, one should be mindful of the semantic and accessibility of the page when styling an HTML page.

One of the main things that many still get wrong is the colour contrast, the default colour scheme of your website must have proper contrast. Remember, if you create a public website, or share links to it, you are effectively asking others to read it, it should not be a burden for them.

Fixing colour contrast used to be a hard thing to do, but now there are many tools that can help one to achieve good colour contrast. One of them is WebAIM: Contrast Checker.

Now that we have decided to be inclusive of people with needs, let us learn how to style a web page!

There are multiple ways to style elements in HTML:

  • Using inline styles by using the style attribute
  • Using the <style> tag inside <head> tag.
  • Using a stylesheet, which is just the contents of the <style> placed in a separate file.

We will be using a stylesheet, which is easier to read, write, and manage. The other ways I mentioned to style HTML documents are usually discouraged as it makes managing styles hard, but feel free to explore how to do them on your own.

Stylesheets

A stylesheet is a simple text file that contain styles in CSS (Cascading Style Sheet) format. The purpose of CSS is to change the look and feel of the web page, but as you learn more about it, you might get tempted to ignore the HTML structure completly, we will try to avoid that here.

CSS is not just for styling HTML, it can be used to style SVG or XML documents, and some graphical user interface toolkits also supports styling via CSS, so it is always good to learn a bit about it.

For styles to work, we need to to tell the browser where to look for it. This is done by adding a link tag within the head. The syntax will look like <link rel="stylesheet" href="/path/to/style.css">. As you might have noticed, link is a void tag, you do not need to close it.

The syntax

The CSS has a very simple syntax, a selector, declaration block, properties, and values. There are also some more advanced things like media queries, but the basics remains the same.

If you decide to have the main heading on your page to be shown in the center with red text, the following code shows a very simple CSS rule that would achieve that styling:
h1 {
  color: red;
  text-align: center;
}
  • In the above example, the CSS rule opens with a selector. This selects the HTML element that we are going to style. In this case, we are styling level one headings (h1).
  • We then have a set of curly braces { }. This is the declaration block
  • Inside the braces will be one or more declarations, which take the form of property and value pairs. We specify the property (color in the above example) before the colon, and we specify the value of the property after the colon (red in this example).
  • This example contains two declarations, one for color and the other for text-align. Each pair specifies a property of the element(s) we are selecting (h1 in this case), then a value that we'd like to give to the property.

Let us create a simple stylesheet first named style.css with the above example. We will create it in the same folder you placed the index.html file to.

Now that we have a simple css file, add it inside the head tag witin the index.html file.

<link rel="stylesheet" href="./style.css">

You will notice that the href is pointing to ./style.css. The . here is to tell that the path is relative to the index.html file, and you will probably never see it on a real website because there are better ways to do this when hosting it. I will talk about that later in this blog, let us focus on the style for now.

Your index.html file should now look like this.

<html lang="en-gb-oxendict">
  <head>
    <meta charset="UTF-8">
    <title>A simple HTML document</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <h1>Welcome to my simple HTML page</h1>
    <p>
      An HTML page is used for sharing information with others. And to ensure that <em>everyone</em> can access the page, we must be conscious of the <strong>semantic</strong> and <strong>accessibility</strong> when writing it.
    </p>
  </body>
</html>

Once you save those files and refresh your browser, the content remains the same, but you will see new the style like below.

Firefox screenshot

The heading Welcome to my simple HTML page is now rendered as a big and heavy text in red. It is aligned to the center of the page.

Understanding selectors

To identify which element to style, we use CSS selectors. This can be its tag name, id, class, or any other attributes.

It is also possible to style an element based on user action like when a user hover over an element, or is curruntly focusing on it with a mouse or keyboard.

The possiblities are endless, so to make a CSS stylesheet easy to read, and to reduce the burden on the browser which calculates how to style things, we should use simple selectors while also avoiding style conflicts.

I am going to provide some examples of selectors here, it might feel a bit overwhelming, but just like HTML elements, you do not need to understand them all. You will gradually learn as you work with them.

We have already seen how to style using an element's tag name, we just write it's tag name, i.e., to style <h1> element, we just write h1 as its selector.

/*Styling all h1 elements */
h1 {
  /* some styles */
}

The text written between /*  and  */ are not considered styles, they are the way to do comments in CSS, and the browser will ignore it.

To style using an element's attribute, we use an attribute selector, a simple attribute selector can be written as [attribute-name="value"].

/* Styling all elements with the title attribute set as "cheese" */
[title="cheese"] {
  /* some styles */
}

Two HTML attributes, id, and class are special, because they are used a lot for styling HTML.
To style using a class, we prefix the class name with a ., so the syntax will be .class-name.
To style using an element's id, we prefix the class name with a #, so the syntax will be #element-id.

/* Styling all elements with the class "cat" */
.cat {
  /* some styles */
}

/* Styling element with the id "mouse" */
#mouse {
  /* some styles */
}

It is also possible to join multiple selectors together, to do that, we just write them together without any space between them.

/* Styling all image elements with the class "cat" */
image.cat {
  /* some styles */
}

If you put a space between selectors, that means that the selector preceeding is a child element. for example, the selector #house .mouse .cheese will style the element with the class cheese which is under an element with the class mouse which is under another element with the id house

/* Styling all elements with the class "cat" inside the element with id "house" */
#house .cat {
  /* some styles */
}

Let us update the style.css file a bit, I'm setting a purple colour for the background, white text colour, removed the attention seeking red heading, and increased the text size for the paragraph.

body {
  background-color: purple;
  color: white;
  line-height: 2em;
}

h1 {
  text-align: center;
}

p {
  font-size: 1.2em;
}

Let us refresh the page again to see new the style.

Firefox screenshot with new changes

The background colour has now changed to purple, all the text, including the title is now in white color. There now a bit more gap between the lines in the paragraph, and its font size has increased sightly.

Now we have a problem, the colours we set might not be readable under some light conditions, and some prefers light theme while others need a dark theme. Some set their system or the browser to automatically change the theme based on time or location. It is one of the very convenient ways to avoid eye strain.

Well, it is not just the visitors, you might also prefer one theme over the other most of the time. While many debate about what is good for the eyes even now, switching between dark and light themes is an accessibility feature, and we are considerate to people with needs, right?

Most modern browsers now support a few convenient ways to tackle this in pure CSS.

Media queries
Media queries allow you to apply CSS styles depending on a device's media type (such as print vs. screen) or other features or characteristics such as screen resolution or orientation, aspect ratio, browser viewport width or height, or user preferences. These may include preferences such as preferring reduced motion, data usage, or transparency.
CSS custom properties (CSS variables)
CSS variables allow you to assign property values and dynamically change it. This is a powerful feature when combined with media queries or JavaScript (A programming language used to make websites more interactive).
color-scheme property
The color-scheme CSS property allows an element to indicate which colour schemes it can comfortably be rendered in. This is intended to help the browser style the form controls like text boxes and buttons, and scrollbars.

I will write more about Media queries and dynamic styling in the next part of this series.

About me

Coding Otaku Logo

I'm Rahul (he/him), the Internet knows me by the name Coding Otaku. I work as a Full-Stack Developer at IBM in London.

I care about Accessibility, Minimalism, and good user experiences. Sometimes I write stories and draw things.

Get my cURL card with curl -sL https://codingotaku.com/cc
Find me on Mastodon, Codeberg, or Peertube.
Subscribe to my feeds.

Continue Reading

Next

All my blogs can be subscribed to using RSS(Atom) or JSON feeds, if you do not know how to use feeds, I have a page with instructions on how to do that.

Comments

You can comment on this post here, all fields except the comment and answer are optional.









Recent Blogs

Subscribe via Atom or JSON feeds.