Question

I have an element with:

position:absolute;
left: 70%;

can I configure element for example to not move from left more than 900px? something like max-width but for positioning?

Was it helpful?

Solution

You can use CSS3 Media Queries to achieve that

So:

#element {
  position:absolute;
  left: 70%;
}

If you don't want it to overlay an object when you have a smaller screen or resize the window, you can add after that:

@media all and (max-width: 980px) {
    #element{
        margin-left: 0px;
        left: 220px;
    }
}

When the screen width is less than 980px, the #element object will be fixed to 220px.

OTHER TIPS

I was able to do this by using the min() function in CSS.

This only works for me because the thing I'm trying to position on the right side has a constant width.

So I've got this...

#rightFloatyThing {
    left: min( calc(100vw - 278px) , 1002px );
}

278px is the width of the floaty thing on the right side. I want to always make sure the right side floaty thing is within view. So it's left position will always at least be the view width minus the right side thing's width.

1002px is the farthest to the right that I want the right side floaty thing to ever get

Edit: Make sure to check the Can I Use for CSS math functions. It wasn't supported in some major browsers until early 2020.

The only way to do this with CSS is to remove the absolute positioning, and float it to the right.

Put an empty "pusher" div, floated left. Give it a width of 70%, and a min-width of 900px; Then float your element beside it.

Otherwise you'll have to use Javascript.

Alternatively you could wrap the absolutely positioned element with a relatively positioned element which has a min-width.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top