How to use absolute positioning In HTML

Absolute positioning in CSS allows elements to be placed relative to their closest positioned ancestor. In this approach, #navbar is set to position: relative, and the logo image (#navbar img) is positioned absolutely at the center using top: 50%, left: 50%, and transform: translate(-50%, -50%).

Example 2: This example illustrates the absolute positioning property of CSS to align a logo to the center of the navigation bar.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
      <title>Align a logo image to Navabr</title>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
 
        #navbar {
            position: relative;
            width: 100vw;
            height: 40px;
            background-color: rgb(61, 59, 59);
        }
 
        #navbar img {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 40px;
            height: 40px;
        }
    </style>
</head>
 
<body>
    <nav id="navbar">
        <img src=
"https://media.w3wiki.org/gfg-gg-logo.svg" alt="Logo image">
    </nav>
</body>
 
</html>


Output:



How to align a logo image to center of navigation bar using HTML and CSS ?

The navigation bar is an essential component of a website that helps users to navigate between different pages. It is usually located at the top of the page and consists of a list of horizontal links, logos, and other elements. The alignment of logos can be adjusted using CSS. In this tutorial, we will focus on how to align the logos to the center of the navigation bar.

Table of Content

  • Using Flexbox
  • Using absolute positioning

Similar Reads

Using Flexbox:

Flexbox simplifies centering a logo in a navbar by applying ‘display: flex’ to the navbar container and using ‘justify-content: center’ for horizontal centering, ensuring a straightforward and responsive layout....

Using absolute positioning:

...