0
votes

I know how to vertically center a div on the screen or in a parent container with flexbox. However, I can't vertically center a div on the remaining screen height.

Basically:

  • I have a page with a header, and just below a div with some content. The content should be vertically centered on the remaining height.
  • When giving height:100vh to the parent wrapper, the div centers, but the parent div becomes too long and overflows the viewport. The centering is thus not correct. When giving the parent a height:100%, it has no effect.

How to fix this? Here is the code and a sandbox:

html:

export default function App() {
  return (
    <div className="App">
      <header>
        <h1>Header</h1>
      </header>
      <div className="content-wrapper">
        <div className="content">
          <h3>content</h3>
        </div>
      </div>
    </div>
  );
}

css:

body {
  margin: 0;
  background: black;
  height: 100vh;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

header {
  padding: 24px;
  color: white;
  border: 1px solid white;
}

.content-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  height: 100%;
}

.content {
  border: 1px solid orange;
  padding: 24px;
  width: 100%;
}

the sandbox: https://codesandbox.io/s/happy-wright-c85gi?file=/src/styles.css

Thanks for your help!

2

2 Answers

1
votes

The content wrapper must fill all the remained screen. so:

.App{
    display: flex;
    flex-direction: column;
    height: 100vh;
 }

.content-wrapper
{
    flex: 1;
    justify-content: center;
    align-items: center;
}
0
votes
/* MIDDLE AND CENTER ELEMENT */
.middle-center {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* IN YOUR CODE */
.content {
  border: 1px solid orange;
  padding: 24px;
  width: 100%;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}