2013-04-22 143 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; 
} 
相关问题