gpt4 book ai didi

html - 如何使用 flex 居中绝对元素?

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:04 27 4
gpt4 key购买 nike

我有主 div,它是 position:relative; 和 children,它是绝对元素。我想将它们水平居中,但发生了一些我不明白的奇怪事情。

如何使用 flex 将绝对元素水平居中?有什么想法吗?

示例图片 enter image description here

body{
background:tomato;
}
.block{
position:relative;
width:700px;
background:white;
padding:10px;
}
.block-item{
width:60px;
height:60px;
position:absolute;
display:flex;
align-items:center;
justify-content:center;
}

.block-item:nth-of-type(1){
left:0;
background:lightgreen;
}
.block-item:nth-of-type(2){
left:5%;
top:25px;
background:lightblue;
}
.block-item:nth-of-type(3){
left:10%;
background:lightgray;
}
  <div id="main">
<div class="block">
<div class="block-item"></div>
<div class="block-item"></div>
<div class="block-item"></div>


</div>
</div>

最佳答案

更新:您也可以使用 marginposition relative

实现此目的

body{
background:tomato;
}
.block{
position:relative;
width:100%;
background:white;
padding:30px 10px 50px 10px;
display:flex;
align-items: center;
justify-content: center;
}
.block-item{
width:60px;
height:60px;
position:relative;
}

.block-item:nth-of-type(1){
background:lightgreen;
left:0;
}
.block-item:nth-of-type(2){
left: -2%;
top: 20px;
background: lightblue;
}
.block-item:nth-of-type(3){
left: -5%;
background:lightgray;
}
<div id="main">
<div class="block">
<div class="block-item"></div>
<div class="block-item"></div>
<div class="block-item"></div>
</div>
</div>

关于html - 如何使用 flex 居中绝对元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com