首页 > 解决方案 > 绝对位置 div 垂直间隔不均匀

问题描述

绝对定位的 div 间隔不均匀。我一遍又一遍地检查计算,但我找不到数学有什么问题。我知道你可以用 flexbox 做到这一点,但我需要用绝对定位来做到这一点。

HTML:

<section class="book">

            <div class="book__side-edit book__side-edit--1" alt="Burger"></div>
            <div class="book__side-edit book__side-edit--2" alt="Burger"></div>
            <div class="book__side-edit book__side-edit--3" alt="Burger"></div>

        </section>

CSS

.book{
    height: 95.625vh;
    background-color: #f2f2f2;
    position: relative;
    overflow: hidden;

    &__side-edit{
        height: 177px;
        width: 177px;
        position: absolute;
        background-color: blue;

        &--1{
            top: calc( (95.625vh - (177px * 3)) / 3);
            left: 0;
            transform: translateX(-50%);
        }

        &--2{
            top: calc( ( (95.625vh - (177px * 3)) / 3 ) * 2);
            right: 0;
            transform: translateX(50%);
        }

        &--3{
            top: calc( ( (95.625vh - (177px * 3)) / 3 ) * 3);
            left: 0;
            transform: translateX(-50%);
        }
    }

}

标签: htmlcsssass

解决方案


我想你忘了添加已经存在的 .side-edit 高度。第二个需要,+ 177px第三个需要+ 354px(或 2 * 177px );

我在片段中为书添加了 531px 的最小高度,以确保所有 3 177px 框的空间,我删除了翻译样式以专注于顶部和高度。因此,我在计算中使用了 100%,但我认为即使您最终没有处理最小高度问题,这种方式也会更干净。

/* 177px * 3 = 531px */

.book {
  height: 95.625vh;
  min-height: 531px;
  background-color: #f2f2f2;
  position: relative;
  overflow: hidden;
}

.book__side-edit {
  height: 177px;
  width: 177px;
  position: absolute;
  background-color: blue;
}



.book__side-edit--1 {
  top: calc( (100% - 531px) * 1 / 3);
  left: 0;
}

.book__side-edit--2 {
  top: calc( (100% - 531px) * 2 / 3 + ( 177px * 1 ) );
  right: 0;
}

.book__side-edit--3 {
  top: calc( (100% - 531px) * 3 / 3 + ( 177px * 2 ) );
  left: 0;
}
<section class="book">

  <div class="book__side-edit book__side-edit--1" alt="Burger"></div>
  <div class="book__side-edit book__side-edit--2" alt="Burger"></div>
  <div class="book__side-edit book__side-edit--3" alt="Burger"></div>

</section>


推荐阅读