简体   繁体   中英

% based, fixed and absolute positioned, nested elements?

Image: 在此处输入图片说明 I have a container div (yellow) which I'd like to keep at 50% width of the window. A child of that container is an image div (purple) that stretches to 100% of the parent container's width. and there's a sticky label (pink) on top of the image div (position: absolute so it can be offset relatively to the image). I'd like to keep that entire half of the screen fixed positioning so it stays sticky as I scroll.

There's also a title under the image, and that title needs to be visible no matter if someone shrinks the window vertically. So in that scenario the image div should shrink vertically, if needed, in order for that title to be shown.

Basically I'm trying to have the image div always be 100% width of the parent container div . With the image div having a max % height so it can shrink vertically. Or have it keep a fixed aspect ratio (3:4 or whatever) when it shrinks vertically.

I'm trying to avoid using fixed pixels, or ems, in the entirety of my CSS. since the website needs to be stretchy/'fluid' vertically, because that title under the image has to show.

HTML looks roughly like:

<wrapper>
    <left-column>
        <normal text and scrollable stuff>
    <right-column-yellow>
        <image sticky label-pink>
        <image div-purple>
        <image title>

Sorry if this is damn confusing my brain is fried! Can anyone pls help me?

You can divide your left and right panel by using position fixed.

If I'm not wrong with your description, this is the answer.

<div class="wrapper">
  <div class="left">
   <p><!--Some very long text--></p>
  </div>
  <div class="right">
    <div class="image">
    <div class="label">Label</div>
    <div class="title">Title</div>
  </div>
</div>

Some CSS

.left,.right{
    position: fixed;
    width: 50%;
    height: 100%;
    display: inline-block;
  }

  .left{
    left:0;
    top: 0;
    overflow: auto;
  }

  .right{
    right: 0;
    top:0;
    background-color: yellow;
  }

  .right .image{
    position: relative;
    width: 100%;
    height: 50%;
    top: 50%;
    left: 0;
    background-color: #fff;
    transform: translateY(-50%);
  }

  .right .image .label{
    position: absolute;
    left: 0;
    right: 0;
    top: -10px;
    text-align: center;
    width: 200px;
    background-color: pink;
    margin: auto;
  }

  .right .image .title{
    position: absolute;
    left: 0;
    right: 0;
    bottom: -40px;
    text-align: center;
    width: 200px;
    background-color: #000;
    margin: auto;
    color: #fff;
    font-size: 30px;
  }

You can refer to my codeine as well. https://codepen.io/masonwongcs/pen/WMJGZb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM