How to use CSS in HTML

Cascading Style Sheets or CSS is used to add styling to webpage. Without styling a webpage won’t look eye catchy. With HTML we can only create a webpage layout but to styles it we need CSS. We can set colors, margin, padding, fonts, size, element positions, visibility, animation etc.

We can use CSS in 3 ways in HTML.

  • Inline
  • Internal
  • External

Inline CSS

CSS can be applied to any element directly using the style attribute. We can assign the required CSS declarations separated by semicolons to style attribute to apply CSS.

<div style="width: 50px; height: 50px; border: 1px solid black">
     some Content
</div>

Internal CSS

If we want define CSS for multiple elements, then we can write all the declarations together inside <style> tag under <head> section.

<html>
<head>
   <style>
     .container {
          width: 50px;
          height: 50px;
          border: 1px solid black;
     }
     #textField {
          padding: 10px;
          border: none;
          height: 30px;
     }
     button {
          border: none;
          background: blue;
          width: 30px;
          height: 20px;
          color: white;
     }
   </style>
</head>
<body>
   <div class="container">
       <input id="textField" type="text" />
       <button> Click </button>
   </div>
</body>
</html>

External CSS

If we want to share the CSS with multiple HTML files, then we can create a separate .css file and include it with the HTML files. We can include an external CSS file in HTML using <link> tag in <header> section.

CSS file

button {
     border: none;
     background: blue;
     width: 30px;
     height: 20px;
     color: white;
}
p {
     font-size: 15px;
     font-family: Arial;
     font-weight: normal;
}
.header {
     margin: 20px;
     padding: 10px;
     font-size: 18px;
     color: white;
     background: blue;
}

HTML file

<html>
  <head>
  <link rel="stylesheet" href="style.css" >
  </head>
  <body>
     <div class="header">
       <p> Some Paragraph text </p>
       <button> Click </button>
     </div>
  </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *