2

http://jsfiddle.net/vT65S/

html:

<div class="container">
    <div class="wide1">test</div>
</div>

<div class="container">
    <div class="wide2">test</div>
</div>

<div class="container">
    <div class="wide3">test</div>
</div> 

CSS:

.container { width: 100%; text-align: center; margin: 20px 0; overflow: hidden; }
.container div { background: red; margin: 0 auto; }

.wide1 { width: 100px; }
.wide2 { width: 600px; } 
.wide3 { width: 1100px; } 

我想在一条垂直线上(居中)进行所有“测试”。我需要在我不知道内部 div 宽度的情况下使用它。

4

3 回答 3

2

以什么为中心?外部容器div?你必须覆盖内部 div 的宽度,比如max-width: 100%.

示例:http: //jsfiddle.net/vT65S/1/

.container div { background: red; margin: 0 auto; max-width: 100% }
于 2012-06-02T10:51:12.193 回答
1

知道了!但是使用 JavaScript ... http://jsfiddle.net/vT65S/10/

jQuery(function($){
    $(".container > *").each(function(){
       var m = ($(this).parent().innerWidth() - $(this).outerWidth())/2;
       $(this).css("margin-left", m);
    });
});

也许有纯 CSS 的解决方案(?)

于 2012-06-03T18:40:00.697 回答
1

遇到同样的问题 - 使用 CSS3 translateX 解决

.container div{
    position: relative;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}
于 2016-07-04T14:31:13.247 回答