【问题标题】:CSS - center big div inside smaller one + hidden overflowCSS - 在较小的一个内居中大 div + 隐藏溢出
【发布时间】:2012-06-07 08:50:37
【问题描述】:

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 宽度的情况下使用它。

【问题讨论】:

    标签: html css overflow positioning


    【解决方案1】:

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

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

    .container div { background: red; margin: 0 auto; max-width: 100% }
    

    【讨论】:

    • 但是这改变了内部div的宽度,如果里面还有其他东西怎么办?例如。图片 - jsfiddle.net/vT65S/4 或只是几段文字?
    • 我不清楚您真正想要发生什么 - 以该图像为例,您希望最终结果是什么样的?另外 - 你再次明确设置图像的宽度,不要忘记max-width他们:jsfiddle.net/vT65S/9
    【解决方案2】:

    知道了!但是使用 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 的解决方案(?)

    【讨论】:

      【解决方案3】:

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

      .container div{
          position: relative;
          left: 50%;
          -webkit-transform: translateX(-50%);
          transform: translateX(-50%);
      }
      

      【讨论】:

      • 干杯,最佳答案在这里。也适用于相对父母和绝对孩子
      猜你喜欢
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 2018-08-13
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多