如何将CSS中的子元素居中,即使它大于父元素?

Ite*_*tor 22 html css css3

我想创建一个css类,以便div可以放在其父级的中心.我使用的代码是:

.centered {
    position: absolute;
    margin: auto;

    bottom: 0px;
    left: 0px;
    top: 0px;
    right: 0px;
}
Run Code Online (Sandbox Code Playgroud)

如果父元素大于子元素,或者具有相同的大小,它可以工作:https: //jsfiddle.net/cy8dn1km/

但是如果孩子比较大,那么它的中心就不会位于其父母的中心.相反,它们的左边界将位于同一位置,而子元素将仅扩展到右边:

https://jsfiddle.net/797L7nce/

水平居中有问题.

如何在不添加新容器元素的情况下仅使用CSS(不使用CSS 2D/3D转换)来修复它?

Ism*_*ooq 18

添加left: 50%; transform: translate(-50%, 0);和删除right: 0px;

.centered {
    position: absolute;
    margin: auto;
    display: block;
    bottom: 0px;
    top: 0px;
    left: 50%;
    transform: translate(-50%, 0);
}
Run Code Online (Sandbox Code Playgroud)

演示


Nen*_*car 15

这是一个不使用CSS 2D/3D转换的解决方案.你可以用display: flexflex-direction: column(这是重要的父元素和)display: table子元素.

body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: green;
}
.centered.d1 {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.d1 {
  background: yellow;
  width: 50px;
  height: 50px;
}
.d2 {
  background: red;
  opacity: 0.7;
  width: 250px;
  height: 250px;
  display: table;
}
Run Code Online (Sandbox Code Playgroud)
<div class="centered d1">
  <div class="centered d2"></div>
</div>
Run Code Online (Sandbox Code Playgroud)


Var*_*ant 5

如果您知道元素的尺寸,则可以使用 50% 的左侧/顶部位置以及元素大小一半的负边距。

我在这里更新了你的小提琴:https ://jsfiddle.net/797L7nce/2/

.centered {
    position: absolute;
    display: block;
    left:50%;
    top:50%;

}

.d1 {
    background: yellow;
    width: 50px;
    height: 50px;
    margin-left:-25px;
    margin-top:-25px;
}

.d2 {
    background: red;
    opacity: 0.7;
    width: 250px;
    height: 250px;
    margin-left:-125px;
    margin-top:-125px;
}
Run Code Online (Sandbox Code Playgroud)