Home > Back-end >  align first element to left in flex box
align first element to left in flex box

Time:10-14

nav {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
}

nav a {
  padding: .4rem;
}

.logo {
  justify-self: start;
  display: block;
}
<nav>
  <a href="/" ><img src="/static/logo.svg" alt="PurelyGigs" /></a>
  <a href="/gigs">Gigs</a>
  <a href="/login">Login</a>
  <a href="/register">Signup</a>
</nav>

I'm trying to align the logo only to the left and the other three nav items to the right using flex-box...without having to use a wrapper

CodePudding user response:

You can use margin-left: auto; for the second link. It also allows for simplification of the rest of your CSS. If you prefer, you can use a class for the second link.

nav {
  display: flex;
}

nav a {
  padding: .4rem;
}

.logo {
  display: block;
}

/* Added */

nav a:nth-child(2) {
  margin-left: auto;
}
<nav>
  <a href="/" ><img src="/static/logo.svg" alt="PurelyGigs" /></a>
  <a href="/gigs">Gigs</a>
  <a href="/login">Login</a>
  <a href="/register">Signup</a>
</nav>

CodePudding user response:

Another way to do this would be using CSS Grid. We declare one column, that has a width of 1fr (fr meaning fraction, more information on this can be found here), meaning it takes up all the space left in the container. This is where the first element - in this case the logo - is added. The other elements get added using grid-auto-flow, which means that elements inside the container that would not fit in the provided columns are inserted in auto generated columns without the previously specified width.

Edit: added links being aligned to the bottom.

nav {
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: 1fr;
  height: 200px;
}

nav a {
  padding: .4rem;
  align-self: end;
}

.logo {
  height:100px;
}
<nav>
  <a href="/" ><img src="/static/logo.svg" alt="PurelyGigs" /></a>
  <a href="/gigs">Gigs</a>
  <a href="/login">Login</a>
  <a href="/register">Signup</a>
</nav>

CodePudding user response:

Please try this

nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

nav a {
  padding: .4rem;
}

.logo {
  justify-self: start;
  display: block;
}
<nav>
  <span>
        <a href="/" ><img src="/static/logo.svg" alt="PurelyGigs" /></a>
    </span>
  <span>
        <a href="/gigs">Gigs</a>
        <a href="/login">Login</a>
        <a href="/register">Signup</a>
    </span>
</nav>

code

  • Related