【问题标题】:When I add this button to my page it offsets the other element that was previously centered [duplicate]当我将此按钮添加到我的页面时,它会偏移以前居中的其他元素 [重复]
【发布时间】:2017-10-05 04:45:11
【问题描述】:

我正在使用 flexbox 设置页面样式。我在一个带有背景图像的 div 中有一个很好地居中的图像。

body {
  width: 700px
}

nav {
  width: 100%;
  height: 50px;
  background-color: #ccc
}

.wrapper,
.banner {
  display: flex
}

.wrapper {
  flex-direction: column
}

.banner {
  background-image: url("https://unsplash.it/1000/600/?random");
  background-repeat: no-repeat;
  background-position: center center;
  height: 300px;
}

.banner img {
  height: 140px;
  width: 140px;
  border-radius: 140px;
  border: 3px solid #fff;
  align-self: center;
  margin: auto;
}
<nav>

</nav>
<article class="wrapper">
  <section class="banner">
    <img id="profile-pic" src="https://unsplash.it/100/100/?random" />
  </section>
</article>

查看此代码笔:

https://codepen.io/efbbrown/pen/PmOpWo


现在我想添加一个 x 按钮,以便用户可以根据需要更改背景图像。当我添加按钮 div 时,它会将居中的图像推离位置。

添加元素:

<section class="banner">
  <div class="close-button"></div>
  <img id="profile-pic" src="https://unsplash.it/100/100/?random"></img>
</section>

查看此代码笔以了解完整的困境:

https://codepen.io/efbbrown/pen/PmOpOq

如何在不更改中心图像位置的情况下将此 x 按钮添加到 div?

谢谢!

【问题讨论】:

    标签: html css flexbox css-position


    【解决方案1】:

    Flex 盒子会根据 flex 元素中包含的项目数量来改变项目的位置和宽度。这意味着当您添加关闭按钮时,您的横幅图像现在基于剩余空间而不是整个宽度居中。您可以通过将项目的位置更改为absolute 从弹性框格式中“删除”项目。该元素现在被 flexbox 忽略,因为它将定位它自己。

    这应该可以解决问题:

    .banner {
        /* ... */
        position: relative;
    }
    
    .close-button {
        /* ... */
        position: absolute;
        /* ... */
    }
    

    编辑

    回答以下 cmets 的问题:绝对定位并不总是由屏幕或窗口的宽度和高度决定。它实际上由最接近的“定位”父级确定,例如标记为position: relative 的父级。

    同时使用相对和绝对是绝对位置真正有效的地方。在此示例中,您可以将横幅类标记为相对位置,并且无论您将该 div 移动到何处,关闭按钮都会跟随并根据横幅 div 定位。

    【讨论】:

    • 有没有办法做到这一点没有位置:绝对?我仍然想相对于其父按钮定位按钮,因为我希望能够更改导航的高度以及横幅上方可能出现的任何其他部分,而无需更改关闭按钮的样式。
    • 绝对定位并不总是由屏幕或窗口的宽度和高度决定。它实际上由标记为position: relative 的最接近的父级确定。将相对位置和绝对位置一起使用是绝对位置真正有效的地方。您可以将横幅类标记为位置relative,然后将该 div 移动到任何位置,关闭按钮将跟随并根据横幅 div 定位。
    • 编辑了我的答案以显示应如何设置横幅类。
    • 哟,就是这样!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 2020-09-24
    • 2017-03-06
    • 2021-02-27
    相关资源
    最近更新 更多