【问题标题】:Center a child <div> to the screen width, not the parent <div>将子 <div> 居中到屏幕宽度,而不是父 <div>
【发布时间】:2011-05-04 21:50:43
【问题描述】:

有一个窄 DIV 包含一个更宽的 DIV。如何在浏览器窗口(而不是父 DIV)中水平居中子 DIV,以使左右边距相等?

<div id="narrow_container" style="float:left;">
     <div id="wide_contents">
     </div>
</div>

【问题讨论】:

    标签: css


    【解决方案1】:

    可能的 CSS:

    <style>
    #narrow_container {display: block; 
       width: 600px; 
       margin: 0 auto;
    } /* narrow div, this can be anything except position: relative */
    #wide_contents {position: absolute;  
       width:400px;
       margin-left:-200px; 
       left:50%; 
    } /* screen-centered div */
    </style>
    

    你基本上只是相对于窗口绝对定位元素,因为绝对定位位置相对于最近的父元素position: relative。如果您没有任何具有position: relative 的父级,它将默认为文档正文。

    居中技术相当普遍,它使用宽度为元素宽度一半的负边距,然后将元素定位在距左侧 50% 的位置。这会产生水平居中的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2012-11-10
      • 2014-12-06
      • 2021-10-13
      相关资源
      最近更新 更多