【问题标题】:Css divs get placed in front of another when abosluteCss div在绝对时被放置在另一个前面
【发布时间】:2020-08-25 01:42:45
【问题描述】:

我有一个 *ngfor 可以制作 div,但是当我制作 div 绝对值时,所有 div 都会放在同一个位置而不是列表中。

我需要将 div 设置为绝对值,以使用相对 css 更改其中的内容。

html:

<ion-grid >
    <div *ngFor="let card of restPointsCards;let i=index" id="card">


      <ion-row>
        <ion-col >
          <ion-img *ngIf="userPercentageCards[i]>= 100" src="../../../assets/icons/PointsCard_100.png" ></ion-img>
          <ion-img *ngIf="userPercentageCards[i]>= 85 && userPercentageCards[i] <100" src="../../../assets/icons/PointsCard_85.png"></ion-img>
          <ion-img *ngIf="userPercentageCards[i]>= 70 && userPercentageCards[i]< 85" src="../../../assets/icons/PointsCard_70.png" ></ion-img>
          <ion-img *ngIf="userPercentageCards[i]>= 50 && userPercentageCards[i]< 70" src="../../../assets/icons/PointsCard_50.png" ></ion-img>
          <ion-img *ngIf="userPercentageCards[i]>= 30 && userPercentageCards[i]< 50" src="../../../assets/icons/PointsCard_30.png" ></ion-img>
          <ion-img *ngIf="userPercentageCards[i]>= 15 && userPercentageCards[i]< 30" src="../../../assets/icons/PointsCard_15.png" ></ion-img>
          <ion-img *ngIf="userPercentageCards[i]< 15 && userPercentageCards[i]> 0" src="../../../assets/icons/PointsCard.png"></ion-img>
        </ion-col>
        <ion-col >
          <ion-text> {{card.cardPoints}} = {{card.cardValue}} € </ion-text>
<!--          <ion-text>{{userPercentageCards[i]}} %</ion-text>-->
          <ion-button id="useButton" *ngIf="userPercentageCards[i] >=100" style="bottom: 0"> Usar Cartão!</ion-button>
        </ion-col>
      </ion-row>

    </div>

css:

#card{
  position: absolute;
  border: #5e8d93 2px solid ;
  margin-top: 5px;
  height: 140px;
  width: 70%
}

我想改变 div 中图像和按钮的位置,这就是为什么我想让 div 绝对值,所以我可以像这样改变按钮:

css:

#useButton{
  position: relative;
  bottom: 5px;
}

【问题讨论】:

    标签: html css grid css-position division


    【解决方案1】:

    这正是position: absolute 所做的,它将一个元素放置在一个绝对位置相对于主体或另一个具有位置的父元素:相对。在这种情况下,使用绝对位置势必会将它们放在div 的同一区域中。

    【讨论】:

    • "我需要使 div 绝对值以使用相对 css 更改其中的内容。"这不是它的工作原理。如果一个 div 是相对的,那么它的父级是绝对的还是相对的都没有关系。但它的工作方式相反。绝对 div 将相对于其具有 position: relative 的父级放置。但是将absolute 用于#card 将意味着所有卡片都放置在相同的绝对位置
    【解决方案2】:

    我不知道您为什么要使用 Position:absolute 元素,但我们假设没有其他冲突。用 div/span 包装 #card 容器并给它一个 class="relative" 您可以包装任何绝对元素,这将允许绝对元素作为静态元素存在并继续流动,但它们是不可预测的。

    将此css类添加到文档中

    .relative{
      position: relative;
      display: inline-block;
      width:100%;
      height:100%;
    }
    

    您可以随意命名该类,但请注意:绝对行为取决于任何元素和样式,假设不涉及其他样式,这应该列出彼此下方的元素,但溢出元素除外。

    无论出于何种原因,我都不推荐绝对元素,因为它们总是会破坏 HTML 的流动,所以除非你绝对必须这样做。考虑使用上面的 css 让元素不重叠。

    如果您想要更有效的解决方案,请考虑使用 Pastebin 或 Codepen,我们可以帮助您在不依赖绝对元素的情况下获得预期的效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多