【问题标题】:css "left" not workingCSS“左”不起作用
【发布时间】:2012-12-19 18:14:28
【问题描述】:

我有 2 个 div,父母和孩子,我希望孩子的左侧(左边框)位于父母的中心。

为什么这段代码不起作用?那是 left: 50% 的孩子,不工作。

<div id="outher">
    <div id="inner">

    </div>
</div>

css:

#outher {
   width: 1000px;
   height: 1000px;
   background-color: #ccc;
}

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   left: 50%;
}

演示http://jsfiddle.net/vrse2/5/

【问题讨论】:

    标签: html css positioning


    【解决方案1】:

    您需要将position 设置为absoluterelative

    #inner {
       width: 400px;
       height: 300px;
       background-color: #090;
       position: absolute;
       left: 50%;
    }
    

    【讨论】:

      【解决方案2】:

      CSS left 仅适用于定位元素。

      Quoted from W3C

      Values  <length> | <percentage> | auto | inherit
      Initial value   auto
      Applies to  positioned elements
      Inherited   No
      

      试试

      #inner {
         width: 400px;
         height: 300px;
         background-color: #090;
         position: absolute;
         left: 50%;
      }
      

      好读

      1. MDN : CSS Reference -left (Best IMHO)
      2. W3C : CSS/Properties/left

      【讨论】:

        【解决方案3】:

        您需要将position: absolute; 添加到您的CSS。 left 用于绝对定位。

        在你的情况下:

        #inner {
           width: 400px;
           height: 300px;
           background-color: #090;
           position: absolute;
           left: 50%;
        }
        

        【讨论】:

          【解决方案4】:

          用途:

          margin-left: 50%;
          

          或者:

          position:relative;
          left:50%;
          

          【讨论】:

          【解决方案5】:

          尝试以下方法:

          HTML 部分:

          <div id="outher">
              <div id="inner">
          
              </div>
          </div>
          

          CSS 部分:

          #outher {
              width: 1000px;
              height: 1000px;
              background-color: #ccc;
          }
          
          #inner {
              width: 400px;
              height: 300px;
              background-color: #090;
              left: 50%;  
              margin:0 auto;
              position: absolute;
          }
          

          我认为这可以帮助您解决问题。

          【讨论】:

            猜你喜欢
            • 2017-07-02
            • 2018-02-15
            • 1970-01-01
            • 2013-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-12-02
            • 2017-05-07
            相关资源
            最近更新 更多