【问题标题】:Specify right margin in fixed positioning在固定定位中指定右边距
【发布时间】:2012-09-10 06:32:15
【问题描述】:

我不知道如何正确命名,但这是我的问题:

我有这个布局:

<html>
<body>
    <div id="content">this is my page</div>
    <div id="button">magic button</div>
</body>
</html>

css:

#button {
  position: fixed;
  bottom: 20px;
  background-color: #f00;
  padding: 5px;
  left: 50%;
  margin-left: 250px;

}

html, body{
  height: 100%;
}
#content {
  margin: 0 auto;
  width: 700px;
  min-height: 100%;
  background-color: #eee;
}​

在此处查看小提琴:http://jsfiddle.net/n6UPF/

我的页面按我的意愿工作,按钮正是我想要的位置。

但是如果我更改按钮上的文本,它的位置将不再正确。

我想将其相对于我的内容区域的右边缘“固定”放置。

这可以在纯 CSS 中完成吗?

【问题讨论】:

    标签: css positioning css-position


    【解决方案1】:

    如果可以接受修改 HTML,则可以使用包装器:

    <div id="button-wrapper">
        <div id="button">magic button</div>
    </div>
    
    #button-wrapper {
        bottom: 40px;
        left: 50%;
        margin-left: 350px;
        position: fixed;
    }
    
    #button {
        background-color: red;
        padding: 5px;
        position: absolute;
        right: 10px;
        white-space: nowrap;
    }
    

    http://dabblet.com/gist/3740941

    不,不是很漂亮,但是……

    【讨论】:

    • 是的,我想我更喜欢这种语义dabblet.com/gist/3740961 少一个 id 担心,span 有点有意义
    • 是的,我真的很讨厌这个。更少是因为包装器,更多是因为white-space: nowrap。我不认为有任何其他方式可能(但如果是的话,我会很高兴的!)。
    • 进一步证明所有 CSS 难题都可以通过添加更多 DIV 来解决。
    【解决方案2】:

    你是说……

    #button
    {
        position: fixed;
        right: 20px;
    }
    

    ...或者右边的任何距离?还是别的什么?

    【讨论】:

    • 对不起,我可能有点不清楚,我希望红色按钮的右边缘距离灰色边框的右边缘 5px。无论按钮中有多少文本。无论对窗口进行多少调整。
    【解决方案3】:

    我不确定我是否完全正确理解了你的问题,但你能不能只使用right 属性而不是left

    示例:http://jsfiddle.net/baKra/

    【讨论】:

      【解决方案4】:

      通常当我遇到精确定位问题时,这是因为我没有指定定位元素的宽度。浏览器会尝试自己计算它,这可能会导致问题发生。

      有什么方法可以发布它不再正确定位时的样子?

      【讨论】:

      • 不能指定宽度,真的不知道,本地化和动态内容决定的。
      【解决方案5】:

      我想知道您是否正在寻找 float:right 属性。 你能看看http://jsfiddle.net/n6UPF/1/,看看是不是你要找的。​​p>

      【讨论】:

        【解决方案6】:

        尝试改变

        #button {
        position: fixed;
        bottom: 20px;
        background-color: #f00;
        padding: 5px;
        left: 50%;
        margin-left: 250px;
        }
        

        #button {
        position: fixed;
        bottom: 20px;
        background-color: #f00;
        padding: 5px;
        right:20px
        }
        

        【讨论】:

        • 查看 minitechs 回答我所追求的确切行为。尝试编辑文本,调整窗口大小,看看会发生什么
        猜你喜欢
        • 1970-01-01
        • 2012-01-16
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 2014-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多