Home » Basic Syntax of CSS: A Beginner’s Guide to Styling Your Website

Basic Syntax of CSS: A Beginner’s Guide to Styling Your Website

by linweichun8711

CSS is a widely used technology in web development and design. It provides a way to add styles and layouts to HTML content, making websites more attractive and user-friendly. This article will cover the basics of CSS, including how to add it to HTML, its basic syntax, and a code example with a linked CSS and HTML file.

How Do You Add CSS to the HTML?

There are two main ways to add CSS to an HTML file: using an internal style sheet or using an external style sheet, internal and external.

  • Internal style sheet

Add <style> tag in an HTML document’s “head” section and write the CSS code.

<head>
  <style>
     your styles...
  </style>
</head>

<body>
  content...
</body>
  • external style sheet

Create a separated CSS file and use <link> to connect.

<head>
  <link href="./style.css" rel="stylesheet" type="text/css">
</head>
//your styles...

Basic Syntax of CSS

CSS consists of selectors and declarations. Selectors are used to selecting the HTML elements you want to style, and declarations are sets of rules that define the styles you want to apply to the selected elements. Each declaration contains a property and a value, separated by a colon and ends with a semicolon. CSS rules are enclosed in curly braces.

selector {
  property: value;
  property: value;
}

Code Example with CSS File and HTML File

Remember the lesson we discussed before? Now it’s your turn to create an HTML file with <div>, <h1>, and <p> in the body. Also, follow the steps in creating a style.css file and adding <link> to the HTML.

<!DOCTYPE html>
<html>
  <head>
    <link href="./style.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <h1>Welcome to Our Website</h1>
    <div>
      <p>
        This is the main content of our website, where you can learn about our
        company and services.
      </p>
    </div>
  </body>
</html>

After it’s linked, let’s start with the heading style. Refresh it and you will see the difference.

h1 {
  color: blue;
  text-align: center;
}

It’s cool, right? Ok, let’s style the <div> and the <p>. So we add two more codes to the file.

h1 {
  color: blue;
  text-align: center;
}
div {
  width: 80%;
  margin: 0 auto;
}
p {
  font-size: 16px;
  line-height: 1.5;
  text-align: justify;
}

Great, you now have a styled website!

Conclusion

CSS is an essential tool for creating visually appealing and user-friendly websites. With a basic understanding of its syntax and how to link it to an HTML file, you can start adding styles to your own websites. Whether you’re a beginner or an experienced developer, CSS provides endless opportunities to enhance the look and feel of your web content.

You may also like