Tobi
Tobi

Reputation: 161

CSS Grid - Centering header section (Logo + Menu)

I am investigating into CSS and Grid right now, as I want to learn new things. Actually, I do have a very simple question (I guess) but I am unable to resolve this. I am trying to use CSS grid for making a simple responsive design. For that purpose, I want to have a header section in which I do have a logo and a menu centered with a maximum width of 1170 px. However, I am unable to center the header-wrapper. Maybe I am doing things wrong here. For a better understanding, I just put a jsiddler here.

https://jsfiddle.net/f7ywrg93/

.wrapper {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows:  100px auto;
  grid-template-areas: 
  "header"
  "promo";
  grid-gap: 10px;
}

.header {
  grid-area: header;
  background-color: #20262e;
  color: #fff;
  font-size: 14px;
}

.promo {
  grid-area: promo;
  background-color: #c0ff3e;
}

.wrapper-header {
  display: grid;
  grid-template-columns: auto auto;
  grid-template-rows: auto;
  grid-template-areas: "logo menu";
  max-width:1170px;
  grid-gap: 20px;
  background-color: #447666;
}

.logo {
  grid-area: logo;
  place-self: start;
  max-width: 300px;
  background-color: #545454;
}

.menu {
  grid-area: menu;
  place-self: end;
  background-color: #eadead;

}
<div class="wrapper">
  <div class="header">
    <div class="wrapper-header">
      <div class="logo">Logo</div>
      <div class="menu">Menu</div>
    </div>
  </div>
  <div class="promo">Promo</div>
</div>

Hope that one can give me some give me some idea what I am doing wrong.

Upvotes: 0

Views: 888

Answers (1)

Dan Knights
Dan Knights

Reputation: 8368

If you swap place-self: start and place-self: end for the logo and menu it will center them:

.wrapper {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows:  100px auto;
  grid-template-areas: 
  "header"
  "promo";
  grid-gap: 10px;
}

.header {
  grid-area: header;
  background-color: #20262e;
  position: relative;
  color: #fff;
  font-size: 14px;
}

.promo {
  grid-area: promo;
  background-color: #c0ff3e;
}

.wrapper-header {
  display: grid;
  grid-template-columns: auto auto;
  grid-template-rows: auto;
  grid-template-areas: "logo menu";
  max-width:1170px;
  width: 100%;
  grid-gap: 20px;
  margin: 0 auto;
  background-color: #447666;
}

.logo {
  grid-area: logo;
  place-self: end;
  max-width: 300px;
  background-color: #545454;
}

.menu {
  grid-area: menu;
  place-self: start;
  background-color: #eadead;
}
<div class="wrapper">
  <div class="header">
    <div class="wrapper-header">
      <div class="logo">Logo</div>
      <div class="menu">Menu</div>
    </div>
  </div>
  <div class="promo">Promo</div>
</div>

place-self positions the elements within their respective grid blocks and not within the container element itself.

Upvotes: 1

Related Questions