【问题标题】:CSS calc(); to position a divCSS 计算();定位一个 div
【发布时间】:2017-06-15 05:58:26
【问题描述】:

我正在尝试创建一个宽度和高度为视图宽度的 37% 的 div。

我希望 div 居中,所以我尝试取 50% 的视图宽度并减去 37% 的值。

然后我希望 div 位于父 div 之外的 50%。它基本上是带有个人资料图像的封面照片。底部位置需要为负数,以便将业务封面徽标强制放在业务视图包装器之外,我能想到的唯一方法是乘以一个负数。

<div class="business-view-cover">
    <div class="business-cover-logo"></div>
</div>

.business-view-cover {
    position: relative;
    height: calc(100vw * 0.5625);
    background-size: cover;
    background-position: center center;
    background-image: url('../images/business-cover-1.png');

    .business-cover-logo {
        position: absolute;
        --width-profile: calc(100vw * 0.37);
        --half-width: calc(var(--width-profile) / 2);
        --profile-bottom: calc(-1 * var(--half-width));
        bottom: calc(var(--profile-bottom) * -1);
        left: calc(50vw - var(--width-profile));
        width: var(--width-profile);
        height: var(--width-profile);
        border: 4px solid $e1-background-grey;
        border-radius: 1.6rem;
        background-size: cover;
        background-position: center center;
        background-image: url('../images/logo-cover-napa.png');
    }
}

使用固定值的示例。

.business-view-cover {
    position: relative;
    height: calc(100vw * 0.5625);
    background-size: cover;
    background-position: center center;
    background-image: url('../images/business-cover-1.png');

    .business-cover-logo {
        position: absolute;
        bottom: -7.65rem;
        left: calc(50vw - 7.65rem);
        width: 15.3rem;
        height: 15.3rem;
        border: 4px solid $e1-background-grey;
        border-radius: 1.6rem;
        background-size: cover;
        background-position: center center;
        background-image: url('../images/logo-cover-napa.png');
    }
}

【问题讨论】:

    标签: css css-position css-calc


    【解决方案1】:

    在了解您的需要后,我编辑了我的答案:要定位您的徽标,请使用 position: relative 并将 bottom 设置为负值,为了使徽标居中,请使用 left: calc(50% - 100px) 其中100px 是徽标大小的一半。

    HTML

    <div class="cover-photo">
        <div class="logo">
        </div>
    </div>
    

    CSS

    .cover-photo{
      width: 100%;
      margin: auto;
      border: 1px solid black;
      text-align: center;
    }
    
    .logo{
      background-color: navy;
      width: 200px;
      height: 200px;
      position:relative;
      bottom: -100px;
      left: calc(50% - 100px);
    }
    

    Example

    另外,CSS 中没有嵌套类,您应该将 .business-cover-logo 移到括号外

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-24
      • 2016-06-01
      • 2010-09-13
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多