css 是否将项目粘贴在上面项目的中心?

hgc7kmma  于 2023-01-03  发布在  其他
关注(0)|答案(3)|浏览(149)

如何将一个项目居中放置在另一个项目的中心?
视觉表示:

[   .   ]     (not centered random item = container-1)
    [.]        (item horizontally centered in relation to the item above = container-2)

<div class="container-1"><img src"https://www.shutterstock.com/image-vector/square-grunge-black-example-stamp-260nw-647778754.jpg></div>
<div class="container-2"></div>
kninwzqo

kninwzqo1#

您可以为两个元素使用 Package 器div,并给定两个margin:auto以在 Package 器容器中对齐它们,并为 Package 器类提供第一个容器所需的对齐方式。
或者,您可以为 Package 类提供flex显示、flex-direction列和align-items to center,并为 Package 类提供第一个容器所需的对齐方式。

/*Say I wanted the first container to positioned 5px from the left of the window. I'd provide this alignment to the wrapper class.*/
.wrapper{
  position: absolute;
  left: 5px;
}
.container-1{
  width: 200px;
  height: 100px;
  background-color: red;
  margin: auto;
}
.container-2{
  width: 100px;
  height: 50px;
  background-color: blue;
  margin: auto;
}
<div class="wrapper">
    <div class="container-1">First Container</div>
    <div class="container-2">Second Container</div>
</div>
yuvru6vn

yuvru6vn2#

你可以使用flex-box属性,设置display属性为flex,使用justify-content:center;使内部div居中。
超文本:

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>demo</title>
</head>
<body>
<div class="container1">
<div class="container2">
</div>
</div>
</body>
</html>

CSS:

.container1
{
 display:flex;
 justify-content:center;
}
ulmd4ohb

ulmd4ohb3#

.

    wrapper{
          display:flex;
    justify-content: center;
    align-items: center;
        }
        .container-1{
          width: 200px;
          height: 100px;
          background-color: red;
          margin: auto;
        }
        .container-2{
          width: 100px;
          height: 50px;
          background-color: blue;
          margin: auto;
        }
<div class="wrapper">
            <div class="container-1">First Container</div>
            <div class="container-2">Second Container</div>
        </div>

相关问题