首页 文章

将div设置为比其父级更宽,而不设置负左边距

提问于
浏览
9

我在div里面有一个div .

内部的div比其父级宽,所以正常程序

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

生成一个内部div,其中子的左边缘与父级的左边缘对齐 .

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

5 回答

  • 3

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

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

    FIDDLE

    <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;
    }
    
  • 7

    您可以使用flexbox:

    .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>
    
  • 0

    我使用变换为绝对元素设计了一个简单的方法 .

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

    如果比父母宽,那么它会居中 .

  • 6

    如果内在是一个图像,我更喜欢这个
    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;

  • 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
    which should be centered </p> </div> </div>

相关问题