2016-12-19 38 views
0

有一個相對寬度(50%)的父容器,以便它響應屏幕的大小。將div垂直固定,但水平距離容器30px遠處

現在,我想要一個按鈕在這個父容器的右下角,它保持垂直固定的。它與position: fixed一起使用,但是當我在不同的設備上查看它時,我無法將其水平定位。

這是我的HTML和CSS

<div class="container"> 
    <div class="button"></div> 
</div> 

.container { 
    position: relative; 
    height: 2000px; 
    width: 40%; 
    margin: 0 auto; 
    background: yellow; 
} 

.button { 
    height: 50px; 
    width: 50px; 
    background: red; 
    position: fixed; 
    bottom: 20px; 
    right: calc(50% - 190px); 
} 

這裏是codepen鏈接http://codepen.io/anon/pen/VmggdO

這看起來不錯,但是當你水平調整屏幕,按鈕應該保持公正30PX黃色容器內水平 - 我如何實現這一目標?請記住 - 當你滾動時,按鈕需要固定垂直放置!

+0

你能解釋一下你想,當你調整窗口的大小發生了什麼?並調整大小?寬度/高度? – Dekel

+0

是的 - 當您水平調整窗口大小時,我希望紅色按鈕在黃色容器內保持30px。 – Ishita

+0

html結構必須是您提供的結構嗎? – Dekel

回答

2

使用絕對位置爲我工作

.button { 
    height: 50px; 
    width: 50px; 
    background: red; 
    position: absolute; 
    bottom: 20px; 
    right: 30px; 
} 

編輯:

隨着「按鈕NEEDS滾動時要保持垂直固定」的新要求,這可以通過改變來實現HTML這樣的:

<div class="container"> 
</div> 
<div class="button-container"> 
    <div class="button"></div> 
</div> 

和CSS來此:

.container { 
    position: relative; 
    height: 2000px; 
    width: 40%; 
    margin: 0 auto; 
    background: yellow; 
} 

.button { 
    height: 50px; 
    width: 50px; 
    background: red; 
    margin-bottom: 20px; 
    float: right; 
    margin-right: 30px; 
    z-index: 100; 
} 

.button-container{ 
    position: fixed; 
    bottom: 0px; 
    width: 40%; 
    left: 0; 
    right: 0; 
    margin-left: auto; 
    margin-right: auto; 
} 

查看更新的代碼筆:http://codepen.io/anon/pen/mOvvgJ

+0

我想保持該按鈕垂直固定 - 也就是說,如果您滾動頁面,按鈕停留在屏幕底部 - 所以,絕對位置不起作用 – Ishita

+0

@Ishita,我更新了我對您更新要求的回答。它確實涉及對html的輕微更改,但我認爲有必要這樣做。 –

+0

哎呀,剛剛意識到我留下了一些測試代碼。更新.... –