Home > other >  Element on top of vertically centered div which does not leave the screen
Element on top of vertically centered div which does not leave the screen

Time:08-26

I have a page with a vertically centered content area. On top of this, I want to have an image, which is relatively positioned to the centered element. I have this setup in a snippet.

let i = 0;

function toggle() {
  document.querySelector('.wrapper').style.height = i   % 2 === 0 ? '300px' : '600px';
}
.wrapper {
  width: 100%;
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.centered {
  background: #F00;
  width: 300px;
  position: relative;
}

.on-top {
  position: absolute;
  margin-bottom: 16px;
  bottom: 100%;
}

button {
  position: absolute;
  top: 0;
  right: 0;
}
<div >
  <div >
    <img  src="https://via.placeholder.com/300x100">
    <h1>Heading</h1>
    <p>
      And some content. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book.
    </p>
  </div>
</div>
<button onclick="toggle()">toggle wrapper size</button>

This is working fine, until the height of .wrapper becomes to small (i.e. on mobile) so that the image on top flows out of view at the top.

So I want to have this layout, but once the image touches the top of wrapper (or body) I want to basically stick it there, so that it does not get cropped off / become completely invisible.

I know how to do this with JS, but would like to avoid running checks on resize. Is there any way to achieve this with pure HTML/CSS?

CodePudding user response:

Use CSS grid to achieve this. I update the code slightly to make the image outside the centered container

let i = 0;

function toggle() {
  document.querySelector('.wrapper').style.height = i   % 2 === 0 ? '300px' : '600px';
}
.wrapper {
  height: 600px;
  display: grid;
  grid-template-rows: 1fr auto 1fr;
  justify-content: center;
  align-items: end;
}

.centered {
  background: #F00;
  width: 300px;
}

.on-top {
  margin-bottom: 16px;
}

button {
  position: absolute;
  top: 0;
  right: 0;
}
<div >
  <img  src="https://via.placeholder.com/300x100">
  <div >
    <h1>Heading</h1>
    <p>
      And some content. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book.
    </p>
  </div>
</div>
<button onclick="toggle()">toggle wrapper size</button>

  • Related