skip to Main Content

I’ve developed a navbar, and I’m attempting to vertically center its items. Despite applying properties for vertical centering, they aren’t taking effect.

This is what I tried

nav{

background-color: rgba(0, 0, 0, 0.5);

height: 40px;

position: sticky;

}

list-style: none;

display: flex;

align-items: center;

justify-content: space-between;

color: white;

2

Answers


  1. It looks like your CSS code snippet is not formatted correctly, but I’ll assume the structure of your HTML and provide an explanation based on the assumption. Assuming you have a <nav> element with a list of items inside, you need to make sure that the CSS properties are correctly applied to the child elements (probably <ul> and <li>).

    Here is an example of how you can structure your HTML and apply the styles to vertically center the items within the navbar:

    nav {
      background-color: rgba(0, 0, 0, 0.5);
      height: 40px;
      position: sticky;
    }
    
    ul {
      list-style: none;
      display: flex;
      align-items: center;
      justify-content: space-around;
      height: 100%; /* Ensure the ul takes the full height of the nav */
      margin: 0; /* Remove default margin */
      padding: 0; /* Remove default padding */
    }
    
    li {
      color: white;
    }
    
    a {
      text-decoration: none; /* Remove underline from links */
      color: white;
    }
    <nav>
      <ul>
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
      </ul>
    </nav>

    In this example, the key is applying the align-items: center; property to the <ul> element to vertically center its child <li> elements. Also, ensure that the height property is set to 100% for the <ul> to take the full height of the <nav> element.

    Make sure your HTML structure matches this, and your CSS should work for vertically centering the navbar items. If you’re still facing issues, please provide more details or correct the formatting of your code snippet for further assistance.

    Login or Signup to reply.
  2. Start with this

    body {
      margin: 0;
    }
    
    nav {
      background-color: rgba(0, 0, 0, 0.5);
      position: sticky;
      list-style: none;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 1em;
    }
    
    nav a {
      color: white;
      text-decoration: none;
    }
    <nav>
      <a href="">One</a>
      <a href="">Two</a>
      <a href="">Three</a>
    </nav>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search