【问题标题】:Center one <div> and float other right [duplicate]居中一个 <div> 并浮动另一个右 [重复]
【发布时间】:2012-10-19 04:11:54
【问题描述】:

可能重复:
Centering one div while another div is floated to the right?

我正在尝试将 container1 居中并将 container2 浮动到它的右侧,以便它稍微离开页面:

示例:http://i.imgur.com/JHkfn.jpg

不幸的是,容器 2 在容器 1 的下方和右侧跳跃,正如您在站点模型中看到的那样(链接在下方。)

网站模型: http://ad313.samrandolphdesign.com/

CSS:

#container1 {
    margin: auto;
    background-color: #FFF;
    width: 80%;
    height: 100%;
    max-width: 600px;
    padding-bottom: 15px;
    display: block;
}

#container2 {
    background-color: #CC9900;
    max-width: 600px;
    width: 80%;
    height: 100%;
    padding-top: 60px;
    padding-bottom: 50px;
    text-align: center;
    float: right;
    display: block;
}

【问题讨论】:

    标签: css html floating


    【解决方案1】:

    尝试使用绝对定位而不是浮动。

    类似:

    #container1 {
        margin: auto;
        background-color: red;
        width: 50%;
        height: 100%;
        max-width: 600px;
        padding-bottom: 15px;
        text-align: center;
        display: block;
        position: absolute;
        left: 25%;
    }
    
    #container2 {
        background-color: #CC9900;
        max-width: 600px;
        width: 50%;
        height: 100%;
        padding-top: 60px;
        padding-bottom: 50px;
        text-align: center;
        display: block;
        position: absolute;
        right: -25%;
    }​
    

    这是jsfiddle 编辑:如果您不想为 container1 进行绝对定位,只需将 top: 0; 添加到 container2

    【讨论】:

    • 这行得通!谢谢!我用你的方式拥抱。
    【解决方案2】:

    将两个 div 包裹在另一个 div 中。并使容器 1 和容器 2 的显示为 inline-block。

    类似的东西。

    <div style="width: 2000px">
      <div id="container1" style="width: 990px; display: inline-block">
      </div>
      <div id="container2" style="width: 990px; display: inline-block">
      </div>
    </div>
    

    试试这个fiddle

    【讨论】:

    • 如果你想要准确的答案,就摆弄它
    • 这只是将 container1 一直扔到左边,而 container1 仍然将自己放置在靠近底部的一个奇怪的地方(但奇怪的是不在 container1 下方)
    • 如何“将 container2 向右浮动,使其稍微离开页面?”
    • 当然,与float bologne 相比,我更喜欢inline-block,但如果必须支持IE8 或更低版本,就会出现问题。这些不支持inline-block,唉。
    • 是的!我通常在最新的浏览器中尝试一切。这可能是问题所在。
    【解决方案3】:

    首先,您需要在标记中将#container2 移动到#container1 上方,这样浮动顶部将是#container1 的顶部,而不是在它之后。其次,你需要给#container2 一个负的margin-right 才能将其移出屏幕。

    #container2 {
    background-color: #CC9900;
    max-width: 600px;
    width: 80%;
    height: 100%;
    padding-top: 60px;
    padding-bottom: 50px;
    text-align: center;
    float: right;
    display: inline-block;
    margin-right: -300px;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 2010-11-19
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2013-02-04
      • 1970-01-01
      相关资源
      最近更新 更多