当比容器宽时,是否可能左右两侧都有DIV溢出?

时间:2014-10-19 03:23:33

标签: html css

我有一系列DIV包含在更大的DIV中。容器DIV高而窄,因此所有子DIV都位于一个垂直列中。

所有子DIV的宽度各不相同,并且所有子div的边距声明都是margin: 0 auto 2em auto;,因此当子DIV没有容器宽时,它就位于水平中心。但是当孩子DIV比容器DIV宽时,孩子的左边缘与容器的左边缘齐平,孩子的右边缘扩展到容器的右边缘。

是否可以改为使得当一个孩子比父DIV宽时,它会同等地扩展到容器的右边缘和左边缘,以便它在视觉上居中?

这是我目前的CSS:

.parent {
    margin: 2em auto;
    width:80%;
    border: red thin solid;
}
.child {
    border: green 3px solid;
    display: table;
    position: relative;
    clear: both;
    line-height:0;
    margin: 0 auto 2em auto;
}

1 个答案:

答案 0 :(得分:0)

http://codepen.io/anon/pen/ItfAc

您可以手动或以编程方式执行此操作,并使用负边距左。

公式非常简单:你取出子div溢出的数量,将其减半,然后将结果作为负边距值。所以,如果你有一个宽度为140%的子div,则margin-left:-20%。

如果你想避免使用JS,那么使用Sass很容易,例如:

@mixin width-overflow($width){
    width: percentage($width/100);
@if ($width > 100) {
    margin-left: -(percentage(($width - 100) * .005));
    }
}

.child-1 {
    @include width-overflow(140);
}

(* .005只是/ 2/100 - 将数字除以100只是为了将其转换回百分比有点混乱,但是很有效。我确信有比这更优雅的方法。 )