Home > Enterprise >  Avoid vertical movement if an empty div gets one line of text
Avoid vertical movement if an empty div gets one line of text

Time:10-18

I have 3 <div> in a column with flex (this layout needs to stay).

How to make that #a and #b take one full line height, even if empty? To prevent everything from moving when one line of text is inserted in #a and #b?

If possible without hardcoding with a fixed number of pixels.

document.getElementById("go").onclick = () => {
   document.getElementById("a").innerHTML = "a";
   document.getElementById("b").innerHTML = "b";
};
#main { 
    height: 150px; 
    display: flex; 
    align-items: center;             /* i want to */
    justify-content: space-around;   /* keep this */
    flex-direction: column; 
    background-color: yellow; 
}
<div id="main">
<div><button id="go">Click me</button></div>
<div><i id="a"></i></div>
<div><i id="b"></i></div>
</div>

CodePudding user response:

Set children height to 100%

document.getElementById("go").onclick = () => {
  document.getElementById("a").innerHTML = "a";
  document.getElementById("b").innerHTML = "b";
};
.main {
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;     /* i want to */
  justify-content: space-around;    /* keep this */
  gap: 5px;    /* you can remove this */
}

.main>div {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background: yellow;    /* you can remove this */
}
<div >
  <div>
    <button id="go">click Me</button>
  </div>
  <div>
    <i id="a"></i>
  </div>
  <div>
    <i id="b"></i>
  </div>
</div>

CodePudding user response:

Your problem is that the children don't have a fixed size, give them a fixed size and it will work fine

document.getElementById("go").onclick = () => {
  document.getElementById("a").innerHTML = "a";
  document.getElementById("b").innerHTML = "b";
};
.main {
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;     
  justify-content: space-around;    
}

.child {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: yellow;    
}
<div  >
  <div ><button id="go">click Me</button></div>
  <div ><i id="a"></i></div>
  <div ><i id="b"></i></div>
</div>

  • Related