skip to Main Content

How can I center the orange box in the remaining visible green area? if the main box is too big for (100vh – 20px * 2 – h of top bar) it should just use the minimum distance to top bar and end of container – here defined as margin.

#container {
  min-height: 100vh;
  background-color: green;
  display: flex;
  flex-direction: column;
}

#topBar {
  background-color: yellow;
  top: 0;
}

#mainBox {
  background-color: orange;
  margin: 20px 0;
}






body {
margin: 0;
}
<div id="container">
  <div id="topBar">Height of this is unknown!<br>.</div>
  <div id="mainBox">Height of this is also unknown. It should be vertically in the center of the REMAINING VISIBLE green area<br>.</div>
</div>

2

Answers


  1. You can use flexbox to center. Something like that should be good

    #container {
      min-height: 100vh;
      background-color: green;
      display: flex;
      flex-direction: column;
    }
    
    #topBar {
      background-color: yellow;
      top: 0;
    }
    
    #mainBox {
      background-color: orange;
      margin: 20px 0;
    }
    
    body {
    margin: 0;
    }
    
    .center {
      display: flex;
      flex: 1;
      align-items: center;
    }
    <div id="container">
      <div id="topBar">Height of this is unknown!<br>.</div>
      <div class="center">
      <div id="mainBox">Height of this is also unknown. It should be vertically in the center of the REMAINING VISIBLE green area<br>.</div>
      </div>
    </div>
    Login or Signup to reply.
  2. You can set the height for the green container setting it to auto, which means that its height will be based on its content length.

    #container {
      min-height: 100vh;
      background-color: green;
      display: flex;
      flex-direction: column;
    }
    
    #topBar {
      background-color: yellow;
      top: 0;
    }
    
    #mainBox {
      background-color: orange;
      margin: auto 0; /*Here is changed*/
    }
    
    
    body {
    margin: 0;
    }
    <div id="container">
      <div id="topBar">Height of this is unknown!<br>.</div>
      <div id="mainBox">Height of this is also unknown. It should be vertically in the center of the REMAINING VISIBLE green area<br>.</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search