Home > Blockchain >  Can't make two div's ocuppie half the space inside its container with flexbox
Can't make two div's ocuppie half the space inside its container with flexbox

Time:09-02

I'm trying to center two divs inside its container with flexbox and it should make it automatically. I've tried using flex: 1 and isn't working. This is my structure.

#opacScreen {
  display: block;
  z-index: 35;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
  height: 100vh;
  width: 100vw;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

#searchbarWindow {
  z-index: 40;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: var(--main-color);
  display: flex;
  flex-direction: column;
}

#divsearchbar {
  background-color: red;
  flex: 1
}

#displaysearch {
  background-color: green;
  flex: 1
}
<div id="opacScreen">
  <div id="searchbarWindow">
    <div id="divsearchbar">
      <label for=""><svg id="imageLens"></svg></label>
      <input id="searchbar" type="" placeholder="Search Device">
    </div>
    <div id="displaysearch">
      <p>No recent searches</p>
    </div>
  </div>
</div>

The results so far. I would want the red and green div to occupy 50% of its parent and the red one is eating almost all the space.

enter image description here

CodePudding user response:

1. display: flex way

For the display: flex with flex-direction: column, you are doing everything right except the flex container will need a fixed height. Simply add a height: 500px to #searchbarWindow you are good to go.

2. display: grid way

In case you don't have a fixed height for the container, you might want to use display: grid instead.

#searchbarWindow {
  display: grid;
  grid-template-rows: repeat(2, 1fr);
}

Here is a codepen of the display: grid way.

  • Related