0

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?

depperm
  • 10,606
  • 4
  • 43
  • 67
N G
  • 15
  • 5

2 Answers2

0

If you put the H1 tag inside a Div tag, you will be able to center the div's content using "text-aling: center;" (The Div must have a defined width).

  • Text would still be centered between 2 elements and not be placed in the middle. You need an absolute position to solve this. – Alfred Kwak Feb 01 '23 at 18:26
0

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>
Alfred Kwak
  • 85
  • 11