Krish
Krish

Reputation: 4242

How to align element at center bottom using flex box

I am beginner and I am trying to align span element at parent element bottom side. For this I used below CSS, but why it's not working:

.sidebarBtn {
  position: absolute;
  top: 0;
  right: -50px;
  width: 50px;
  height: 500px;
  border: none;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  background-color: beige;
  outline: none;
  cursor: pointer;
}

.sidebarBtn span {
  width: 35px;
  height: 3px;
  background-color: black;
}
<button class="sidebarBtn">
  <span></span>
</button>

Upvotes: 0

Views: 55

Answers (2)

kukkuz
kukkuz

Reputation: 42352

Use a column flexbox and align it to bottom using justify-content: flex-end - see demo below:

.sidebarBtn {
  position: absolute;
  top: 0;
  right: 50px;
  width: 50px;
  height: 500px;
  border: none;
  display: flex;
  flex-direction: column; /* ADDED */
  justify-content: flex-end; /* CHANGED */
  align-items: center; /* CHANGED */
  background-color: beige;
  outline: none;
  cursor: pointer;
}

.sidebarBtn span {
  width: 35px;
  height: 3px;
  background-color: black;
}
<button class="sidebarBtn"><span></span></button>

But you'd think why your code wasn't working when it would work fine for a div but not a button element in this case - that is because button or fieldset elements are not designed to be a flex container. See how everything is normal when you keep the flexbox inside the button:

.sidebarBtn {
  background-color: beige;
  outline: none;
  cursor: pointer;
  position: absolute;
  top: 0;
  right: 50px;
  width: 50px;
  height: 500px;
}

.sidebarBtn>span {
  border: none;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 100%;
}

.sidebarBtn>span>span {
  width: 35px;
  height: 3px;
  background-color: black;
}
<button class="sidebarBtn">
  <span>
    <span></span>
  </span>
</button>

Upvotes: 2

HamzStramGram
HamzStramGram

Reputation: 437

I think button cannot be flex containers, they can only be flex elements.

This code should work but I'm not sure if that's the best way to do it. It works on Chrome, you might have to try on different browsers.

.sidebarBtn {
  width: 50px;
  height: 500px;
  border: none;
  background-color: beige;
  cursor: pointer;
}

.sidebarBtnContent {
  width:100%;
  height: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.sidebarBtnContent span {
  width: 35px;
  height: 3px;
  background-color: black;
}
<button class="sidebarBtn">
  <span class="sidebarBtnContent">
    <span></span>
  </span>
</button>

Upvotes: 0

Related Questions