htmlcssreactjsposition

Stretch the height of the parent to the height of the absolute element with css


I have a section element which should be floated above the header. But should not hide the footer below. Is there a way to do it using css alone?

function App() {
  return (
    <div className="container">
      <header>
        <h1>Header</h1>
      </header>

      <div className="absolute-child">
        Absolute child with dynamic content. .
      </div>

      <footer>
        <h2>Footer</h2>
      </footer>
    </div>
  );
}

The div absolute-child has dynamic content and its height can vary.

body,
html {
  margin: 0;
  padding: 0;
}

header {
  background-color: violet;
  height: 20rem;
}

.absolute-child {
  background-color: aquamarine;
  position: absolute;
  top: 3.5rem;
  width: 90%;
  padding: 1rem;
  height: 120vh;
}

footer {
  background-color: lightcoral;
  text-align: center;
  padding: 1rem;
}

How to fix it with css so that the footer is not hidden when the height of the absolute-element increase?

Tried using a ghost element along with the absolute element to stretch the height but it doesnt seem to work.


Solution

  • Remove the position: abolute; top: 3.5rem; and use translate: 0 -1.5rem; to paint the element over the header:

    body,
    html {
      margin: 0;
      padding: 0;
    }
    
    header {
      background-color: violet;
    }
    
    .absolute-child {
      translate: 0 -1.5rem;
      background-color: aquamarine;
      width: 90%;
      padding: 1rem;
      height: 120vh;
    }
    
    footer {
      background-color: lightcoral;
      text-align: center;
      padding: 1rem;
    }
    <div class="container">
      <header>
        <h1>Header</h1>
      </header>
    
      <div class="absolute-child">
        Absolute child with dynamic content. .
      </div>
    
      <footer>
        <h2>Footer</h2>
      </footer>
    </div>