【问题标题】:CSS float "hug center"?CSS浮动“拥抱中心”?
【发布时间】:2012-04-09 19:42:03
【问题描述】:

我有两个不同的 div,一个向左浮动,一个向右浮动。它们比整个页面小得多(每个大约 400x200),因此两者相距甚远,紧贴页面边缘。我怎样才能让它们在中心彼此相邻?我尝试将边距分别设置为自动和大约 20px,但它没有改变任何东西..

【问题讨论】:

  • jsfiddle.net 上重新创建您的问题并将其粘贴到您的问题中。

标签: css html css-float margins


【解决方案1】:

这是inline-block的工作!

http://jsfiddle.net/hyw6P/

<div id="container">
    <div id="left">Left!</div>
    <div id="right">Right!</div>
</div>​

#container{
text-align:center;
width:100%;
height:300px;
border:1px solid black
}
#left{
border:3px solid blue;
height:100px;
width:100px;
margin:auto;
display:inline-block;
}
#right{
border:3px solid red;
height:100px;
width:100px;
margin:auto;
display:inline-block;
}​

【讨论】:

    【解决方案2】:

    给他们一个父 div 与 "margin: 0 auto; width:1000px;"

    <div style="margin:0 auto; width:1000px;">
         <div style="float:left">Left</div>
         <div style="float:right">Right</div>
    </div>
    

    或者,如果您希望它们彼此相邻:

    <div style="margin:0 auto;">
         <div style="float:left">Left</div>
         <div style="float:left">Right</div>
    </div>
    

    【讨论】:

    • 你测试过这个吗?这不是 OP 所追求的。
    • @j08691 我当然测试过了,这就是我解释他的请求的方式。
    【解决方案3】:

    在它们周围添加一个包装器 div。在包装器上设置宽度并将顶部和底部边距设置为 0,将左右边距设置为自动。然后设置两个浮动 div 的宽度以适合包装器,例如50% 将使它们具有相同的宽度。

    【讨论】:

      【解决方案4】:

      尝试使用 z-index 和绝对位置或相对位置

      这里有帮助你的链接

      <div style="position: absolute; left: 610px; top: 80px; height: 400px; width: 100px; padding: 1em;">layer stuff</div>
      

      http://www.yourhtmlsource.com/stylesheets/csslayout.html

      http://www.w3schools.com/html/default.asp

      http://www.w3schools.com/html/default.asp

      【讨论】:

        【解决方案5】:

        您可以使用包装 div 并将子 div 设置为显示为内联块来完成此操作。

        CSS:

        #a, #b{
            border: 1px solid #999;
            width: 100px;
            display:inline-block;
        }
        ​#container {
            text-align:center;
        }​
        

        HTML:

        <div id="container">
            <div id="a">a</div>
            <div id="b">b</div>
        </div>
        

        jsFiddle example.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-28
          • 2013-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多