Reputation: 4984
I have a jsfiddle here https://jsfiddle.net/ajvvjnq3/
Really simple, I have a div with fixed width, position fixed and centered.
Below 600px I want the div to be 100% width with 20px margin left and right.
I can't get 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>
Upvotes: 0
Views: 188
Reputation: 475
calc() makes it easy to position an object with a set margin. In this example, the CSS creates a banner that stretches across the window, with a 20-pixel gap between both sides of the banner and the edges of the window
JSFIDDLE
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);
}
}
Upvotes: 0
Reputation: 3841
JSfiddle https://jsfiddle.net/ajvvjnq3/2/
You could try using calc
width: calc(100% - 40px);
seems to work fine
All its doing here is just negating the values from your margins.
Edit
Alternative would be to use @CBroe answer as it supports more browsers than calc
, but whatever floats your boat:)
@media only screen and (max-width: 600px){
.block{
left: 20px;
right: 20px;
width: auto;
margin: auto;
}
}
Upvotes: 3
Reputation: 7701
Try this replace width:100%;
with width:initial;
add 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;
}
}
Upvotes: 0
Reputation: 96306
I’d simply used this:
@media only screen and (max-width: 600px){
.block{
left: 20px;
right: 20px;
width: auto;
margin: auto;
}
}
Positioning the element 20px
from left
and right
, and setting width
to auto
will make it get the right width while respecting the “gap” you want it to have on either side. And margin: auto
(0
would work as well) simply undoes the margin you used earlier to center the element.
https://jsfiddle.net/ajvvjnq3/4/
Upvotes: 3
Reputation: 1093
Try this, it will work..
@media only screen and (max-width: 600px){
.block{
left: 0 !important;
margin: 0 !important;
position: relative !important;
right: 0 !important;
width: 100% !important;
}
}
Upvotes: 0