2015-10-14 107 views
0

我這裏有一個的jsfiddle https://jsfiddle.net/ajvvjnq3/CSS - responsivly中心股利,位置固定

真正簡單的,我有固定的寬度股利,位置固定和居中。

低於600px我希望div是100%寬度,左右各有20px的邊距。

我不能讓margin-right: 20px;

.block{ 
 
    background: red; 
 
    height: 100px; 
 
    position: fixed; 
 
    top: 50px; 
 
    left: 50%; 
 
    margin-left: -200px; 
 
    width: 400px; 
 
} 
 

 
@media only screen and (max-width: 600px){ 
 
    .block{ 
 
     left: 0; 
 
     margin-left: 20px; 
 
     margin-right: -20px; 
 
     width: 100%; 
 
    } 
 
}
<div class="block"></div>

+0

你是什麼意思「我無法獲得'margin-right:20px;'」? – Passerby

+0

margin-right:20px;不起作用,它衝到右側 – ttmt

+0

@ttmt:嘗試我在下面回答的代碼,它將有望解決您的問題。 – CreativePS

回答

3

的jsfiddlehttps://jsfiddle.net/ajvvjnq3/2/

你可以嘗試使用鈣

width: calc(100% - 40px);似乎做工精細

它在這裏做的只是否定您的利潤。

編輯 替代方案是因爲它支持超過calc更多的瀏覽器使用@CBroe答案,但不管你的船浮筒:)

@media only screen and (max-width: 600px){ 
    .block{ 
     left: 20px; 
     right: 20px; 
     width: auto; 
     margin: auto; 
    } 
} 
+0

[有幾個瀏覽器會被留下](http://caniuse.com/#feat=calc)。主要是Android – Passerby

+1

ie8 - 我可以住在那個http://caniuse.com/#search=calc – ttmt

0

試試這個,它會運行

@media only screen and (max-width: 600px){ 
    .block{ 
    left: 0 !important; 
    margin: 0 !important; 
    position: relative !important; 
    right: 0 !important; 
    width: 100% !important; 
    } 
} 
+0

我不認爲他們想要相對定位(原始小提琴仍然明確固定設置)。每個物業都有什麼「重要」?這沒有必要。 – CBroe

3

我只是用這個:

@media only screen and (max-width: 600px){ 
    .block{ 
     left: 20px; 
     right: 20px; 
     width: auto; 
     margin: auto; 
    } 
} 

leftright定位元素20px,並設置widthauto將使其獲得合適的寬度,同時尊重「差距」,你希望它有任何一方。並且margin: auto0也可以工作)只是取消了之前用於居中元素的邊距。

https://jsfiddle.net/ajvvjnq3/4/

0

嘗試此替換width:100%;width:initial;添加right:0;

@media only screen and (max-width: 600px){ 
    .block{ 
     position: fixed; 
     top: 50px; 
     left: 0; 
     margin-left: 20px; 
     margin-right: 20px; 
     right:0; 
     width:initial; 


    } 
} 

Demo Here

0

計算值()可以很容易地定位與一組餘量的對象。在這個例子中,CSS創建跨越窗口延伸,具有的jsfiddle橫幅的兩側,並且該窗口的邊緣

之間的20像素的間隙的橫幅

http://jsfiddle.net/DhwaniSanghvi/okvoLuu5/

<div class="block"></div> 



.block{ 
    background: red; 
    height: 100px; 
    position: fixed; 
    top: 50px; 
    left: 50%; 
    margin-left: -200px; 
    width: 400px; 
} 

@media only screen and (max-width: 600px){ 
    .block{ 
     position: fixed; 
     top: 50px; 
     margin-left: 20px; 
     margin-right:20px; 
     left:0; 
     width: calc(100% - 40px); 
    } 
}