垂直对齐具有固定定位的div

时间:2014-07-30 15:06:37

标签: html css css-position

我是stackoverflow的新手,已经搜索了其他一些答案并尝试了很多不同的东西,但似乎无法做到正确。

我需要垂直对齐隐藏消息'带有文本段落的按钮,使按钮出现在文本旁边的中心(jsFiddle链接下面)。该按钮还需要与页面上的另一个div对齐,因此它必须具有:

position: fixed;
right: 50px;

我遇到的一些其他解决方案的主要问题是,如果缩小浏览器,它不会与文本保持垂直对齐:

http://jsfiddle.net/d3R6v/2/

1 个答案:

答案 0 :(得分:1)

我不认为position: fixed;是一种方法,而不是使用fixed您应该使用absolute但在此之前position: relative;分配给#hideMessage父元素并将您的#hideMessage { display: inline-block; padding: 5px 10px; background-color: #555; color: #fff; cursor: pointer; position: absolute; right: 50px; top: 50%; margin-top: -15px; /* Negate 1/2 the total height of the button, this value currently is approx */ } 修改为

position: absolute;

Demo

我坚持fixed的原因是因为它会与父元素相关联,而使用display: table;则相对于视口。

有关定位的更多信息,您可以refer my answer here


如果您有动态文字

为了更清洁的解决方案,如果你对父元素使用display: table-cell;,对子元素使用display: table-cell;,对按钮的父元素即现在{{1>会更好}},您可以使用vertical-align: middle;将按钮垂直对齐到左侧的动态文本,也可以使用调整大小,按钮不会与文本重叠。

Demo 2

#parent {
    background-color: #bbb;
    color: #fff;
    width: 100%;
    padding: 10px;
    display: table;
}
#text {
    width: 80%;
    display: table-cell;
}
#hideMessage {
    display: table-cell;
    color: #fff;
    cursor: pointer;
    vertical-align: middle;
    text-align: center;
}

#hello {
    background-color: #555;
    padding: 5px 10px;
    white-space: nowrap; /* Add if you want to prevent the 
                            button to wrap on resize */
}
相关问题