居中div比其父更宽,不设置负左边距 [英] Centering div that is wider than its parent without setting negative left margin

查看:98
本文介绍了居中div比其父更宽,不设置负左边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div里面有一个div。



里面的div比它的父元素宽,所以正常的过程

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

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

当人们回答这个问题时,他们使用负的左边距方法。是否有更清洁的解决方案?

解决方案

如何使用 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;
}


I have a div inside a div.

The div inside is wider than its parent so the normal procedure

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

produces an inner div where the left edge of the child aligns with the left edge of the parent.

When people answers this question, they uses to go for the negative left margin approach. Is there a cleaner solution?

解决方案

How about using position: absolute; with left:0;right:0; and margin: auto;

Also, you'll need to place position: relative; on a parent element which has greater width than the outer element. (In the fiddle below it's relative to the body by default)

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

这篇关于居中div比其父更宽,不设置负左边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆