Search code examples
htmlcssheadernavbar

HTML / CSS: How to center element horizontally?


I am trying to create a navbar / header, but I am having some trouble centering an h1-element. This is my HTML:

body {
  margin: 0;
  padding: 0;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 2%;
}

nav {
  display: flex;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
}

li {
  margin-right: 10px;
}

h1 {
  margin: 0;
  text-align: center;
  flex-grow: 1;
}

button {
  display: inline-block;
}
<header>
  <nav>
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </nav>

  <h1>SalonM</h1>

  <button>Button</button>

</header>

To be clear, I do not want to center the h1-element relative to the header, I want to center it in regards to the screen.

Any ideas on how to fix this?


Solution

  • Try this:

      body {
        margin: 0;
        padding: 0;
      }
    
    
      .nav-logo {
        position: absolute;
        display: flex;
        justify-content: center;
        width: 100%;
        height: 100px;
        align-items: center;
    
      }
    
      .nav-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 2%;
        height: 100px;
      }
    
      nav {
        display: flex;
      }
    
      ul {
        list-style: none;
        margin: 0;
        padding: 0;
        display: flex;
      }
    
      li {
        margin-right: 10px;
      }
    
      h1 {
        margin: 0;
        text-align: center;
        flex-grow: 1;
      }
    
      button {
        display: inline-block;
      }
    <header>
        <div class="nav-logo">
          <h1>SalonM</h1>
        </div>
        <div class="nav-wrapper">
          <nav>
            <ul>
              <li>Item 1</li>
              <li>Item 2</li>
              <li>Item 3</li>
            </ul>
          </nav>
    
    
          <button>Button</button>
        </div>
      </header>