当宽度> 100%时,如何在flexbox中居中?

时间:2018-01-11 10:48:07

标签: html css flexbox

我想在我的网站上居中<div>,但我将宽度定义为130%,现在它不再居中了。

知道我怎么能做到这一点吗?

这是我写的:

&#13;
&#13;
.out {
  width: 400px;
  height: 400px;
  border: 1px solid green;
}
.big {
  width: 130%;
  height: 130%;
  /* Pete's suggestion */
  position:relative;           /* add this so the left: 50% works */
  left:50%;                    /* move to middle of div */
  transform: translateX(-50%); /* move back left by half of own width */
  border: 1px solid blue;
}
div {
  display: flex;
}
.center {
  justify-content: center;
  border: 1px solid red;
}
&#13;
<div class="center">
  <div class="out">
    <div class="big">
      Something
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

JSFiddle

2 个答案:

答案 0 :(得分:1)

您可以使用变换的相对定位。这是一个例子:

&#13;
&#13;
.outer {
  /* just for demo */
  width: 200px;
  margin: auto;
  border: 1px solid blue;
}

.inner {
  width: 130%;
  position:relative;           /* add this so the left: 50% works */
  left:50%;                    /* move to middle of div */
  transform: translateX(-50%); /* move back left by half of own width */
  border: 1px solid green;
  height: 20px;
}
&#13;
<div class="outer">
  <div class="inner">

  </div>
</div>
&#13;
&#13;
&#13;

更新,因为您添加了一些代码:

&#13;
&#13;
.out {
  width: 400px;
  height: 400px;
  margin: 200px;
  border: 4px solid lime;
}

.big {
  width: 130%;
  height: 130%;
  border: 4px solid blue;
  
  /* horizontal and vertical center (see above snippet if you only want to horizontally center) */
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  
  /* center the contents of this div */
  display: flex;
  justify-content: center;
  align-items: center;
}
&#13;
<div class="out">
  <div class="big">
    Sonething
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

使用:

margin: 0 auto

在css div中心

相关问题