【问题标题】:% based, fixed and absolute positioned, nested elements?% 基于、固定和绝对定位的嵌套元素?
【发布时间】:2018-02-21 03:11:34
【问题描述】:

图片: 我有一个 容器 div(黄色),我想将其保持在窗口宽度的 50%。该容器的子容器是一个图像 div(紫色),可拉伸到父容器宽度的 100%。并且在图像 div 的顶部有一个粘性标签(粉红色)(位置:绝对,因此可以相对于图像偏移)。 我想保持整个屏幕的一半固定位置,这样它在我滚动时保持粘性。

图片下方还有一个标题,无论有人垂直缩小窗口,该标题都需要可见。因此,在这种情况下,如果需要,image div 应该垂直收缩,以便显示该标题。

基本上,我试图让图像 div 始终为父 容器 div 的 100% width。图像 div 具有 max % 高度,因此它可以垂直收缩。或者让它在垂直收缩时保持固定的纵横比(3:4 或其他)。

我试图避免在整个 CSS 中使用固定像素或 ems。因为网站需要垂直拉伸/“流动”,因为图像下方的标题必须显示。

HTML 大致如下:

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

对不起,如果这该死的令人困惑,我的大脑被炸了!谁能帮帮我?

【问题讨论】:

    标签: javascript html css frontend


    【解决方案1】:

    您可以使用固定位置来划分左右面板。

    如果我的描述没有错,这就是答案。

    <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>
    

    一些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;
      }
    

    你也可以参考我的可待因。 https://codepen.io/masonwongcs/pen/WMJGZb

    【讨论】:

    • 太棒了!完全没想到两边都用固定。很好的解决方案。使用像这样的全固定布局会出现问题吗?这很平常吗?
    • 这取决于您要实现哪种布局。在这种情况下,我认为没问题。
    猜你喜欢
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    相关资源
    最近更新 更多