2013-04-22 141 views
-1

我有一個分配給它的position: relative的容器div,在這個div裏面我有一個錨定標記,它有position: fixed分配給它。相對於其父母div而言,它定位於身體而不是<a>。任何人都可以解釋我如何解決這個問題?爲什麼我的元素靜態位置不相對於父div的位置?

小提琴:http://jsfiddle.net/DWMTn/

CSS

*{padding:0;margin:0;} 

.main { 
    width: 300px; 
    position: relative; 
    background: #eee; 
} 

p { 
    margin-bottom: 20px; 
} 

.btn { 
    display: block; 
    width: 100px; 
    height: 100px; 
    background: red; 
    color: white; 
    text-align: center; 
    line-height: 100px; 
    position: fixed; 
    right: 0; 
    bottom: 0; 
} 

回答

1

正如其他人所說,position:fixed是相對於視口,所以你無法實現你想與CSS單獨。如果你想保持btn固定到main容器,那麼你將需要使用一點JavaScript的絕對定位。

在這個例子中,我已經使用了jQuery庫點動按鈕:

http://jsfiddle.net/DWMTn/7/

var main = $('.main:eq(0)'); //would be better to use an id here 
var button = $('.btn:eq(0)'); //would be better to use an id here 
var max = main.height() - button.height(); 

button.css('bottom', 'auto'); //removes the original bottom positioning 

function moveButton() { 
    var top = $(window).scrollTop() + $(window).height() - button.height(); 
    if (top > max) { 
     top = max; 
    } 

    button.css('top', top + 'px'); 
} 

moveButton(); 

$(window).scroll(function() { moveButton(); }); 
$(window).resize(function() { moveButton(); }); 
1

固定位置元素相對於瀏覽器窗口被定位。

0

你是不是你想要如何佈局的行爲清楚,但我敢打賭有CSS方法來解決它。如果您希望它留在右下角:

.btn { 
    display: block; 
    width: 100px; 
    height: 100px; 
    background: red; 
    color: white; 
    text-align: center; 
    line-height: 100px; 
    position: fixed; 
    left: 200px; 
    bottom: 0; 
} 

您還可以使用邊距來進一步定位元素。例如,如果你想讓它居中:

.btn { 
    display: block; 
    width: 100px; 
    height: 100px; 
    background: red; 
    color: white; 
    text-align: center; 
    line-height: 100px; 
    position: fixed; 
    left: -50px; 
    margin-left: 50%; 
    bottom: 0; 
} 
相關問題