我正在使用 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 中?
谢谢!
最佳答案
Flex 框将根据 Flex 元素内包含的元素数量更改元素的位置和宽度。这意味着当您添加关闭按钮时,您的横幅图像现在基于剩余空间而不是全宽度居中。您可以通过将元素的位置更改为绝对
来从 Flexbox 格式中“删除”元素。该元素现在被 Flexbox 忽略,因为它将定位它自己。
这应该可以解决问题:
.banner {
/* ... */
position: relative;
}
.close-button {
/* ... */
position: absolute;
/* ... */
}
编辑
回答以下评论中的问题:绝对定位并不总是由屏幕或窗口的宽度和高度决定。它实际上是由最接近的“定位”父级确定的,例如标记为 position:relative
的父级。
结合使用相对和绝对位置才是绝对位置真正有效的地方。在此示例中,您可以将横幅类标记为相对位置,无论您将该 div 移动到哪里,关闭按钮都会跟随并根据横幅 div 进行定位。
关于html - 当我将此按钮添加到页面时,它会偏移之前居中的其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826334/