20

我在 div 中有一个 div。

里面的 div 比它的父级宽所以正常的过程

margin-left: auto;
margin-right: auto;

生成一个内部 div,其中子元素的左边缘与父元素的左边缘对齐。

当人们回答这个问题时,他们习惯于采用负左边距方法。有更清洁的解决方案吗?

4

5 回答 5

18

您可以使用弹性盒:

.outer {
  display: flex; /* Magic begins */
  justify-content: center; /* Center contents */
  width: 400px;
  height: 400px;
  background: beige;
  margin: 0 auto;
}
.inner {
  flex-shrink: 0; /* Don't shrink it even if it's too wide */
  width: 600px;
  height: 200px;
  background: pink;
}
<div class="outer">
  <div class="inner"></div>
</div>

于 2016-05-09T22:10:59.857 回答
11

我使用变换为绝对元素制定了一种简单的方法。

left: 50%;
transform: translateX(-50%);

如果比父级更宽,则将其居中。

于 2018-09-14T15:27:54.853 回答
6

如何使用position: absolute;withleft:0;right:0;margin: auto;

此外,您需要放置position: relative;在宽度大于外部元素的父元素上。(在下面的小提琴中,默认情况下它是相对于主体的)

小提琴

<div class="outer">
    <div class="inner"></div>
</div>

css

.outer
{
    width: 400px;
    height: 400px;
    background: beige;
    margin: 0 auto;

}
.inner
{
    width: 600px;
    height: 200px;
    background: pink;
    position: absolute;
    left:0;right:0;
    margin: auto;
}
于 2013-08-19T09:14:41.173 回答
0

如果内部是图像,我更喜欢这个
background: url("../img/pic.jpg") no-repeat center center fixed; -moz-background-size: cover; -webkit-background-size: cover; -o-background-size: cover; background-size: cover;

于 2016-05-09T22:59:12.193 回答
0

见这个网站:http ://www.greywyvern.com/?post=323

即使页面比子 div 窄也可以工作。

div#context {
  border:1px solid blue;
  width:400px;
  margin:0px auto;
}
div#context div {
  position:relative;
  right:50%;
  text-align:center;
}
div#context div p {
  border:1px solid green;
  width:450px;
  height:50px;
  display:inline-block;
  margin-right:-100%;
}
<div id="context">
  Page centering context
  <div>
<p>
  This is the child element<br />
  which should be centered
</p>
  </div>
</div>

于 2018-11-07T13:10:18.887 回答