How to style a header with CSS?


The padding property plays a major role while styling headings. Also, use the text-align property to center the text on a header. Remember to place the header in a separate div container. Let us see how to style a header with HTML and CSS.

Set the header div

Create a div for the header so that we can style it later with CSS −

<div class="header">
   <h1>My website ⇅</h1>
</div>

Style the header div

The header is styled like this −

.header {
   padding: 30px;
   text-align: center;
   background: #bc1a6b;
   color: white;
   font-size: 30px;
}

Set the padding area

The padding area is set on all the four sides of an element at once using the padding property −

padding: 30px;

Align the header text

The header text is aligned to the center using the text-align property with the value center −

text-align: center;

Example

To style a header using CSS, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <title>Page Title</title>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
         margin: 0;
      }
      .header {
         padding: 30px;
         text-align: center;
         background: #bc1a6b;
         color: white;
         font-size: 30px;
      }
      main {
         padding: 20px;
         font-size: 18px;
      }
   </style>
</head>
<body>
   <div class="header">
      <h1>My website ⇅</h1>
   </div>
   <main>
      <h1>Some heading</h1>
      <p>Some sample content.Some sample content.</p>
      <p>Some sample content.Some sample content.</p>
      <p>Some sample content.Some sample content.</p>
   </main>
</body>
</html>

Updated on: 21-Dec-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements