How to "cancel" out left/right for absolutely positioned element?
Asked Answered
B

2

5

I have a div that is positioned absolutely and I gave it a left position.

For desktop it is necessary to have the left position of 100px.

But for tablet I want to push it all the way to the right.

To achieve this I tried doing right: 0, but since left: 100px is already defined in the CSS, the right: 0 does not push it all the way to the right as intended.

Then I tried doing left: 0 in tablet to cancel out the effect that it has but that didn't work either.

Is there a way to cancel out the left position? Something like left: none (I know that does not work but it's the only way I am able to explain this.)

Desktop CSS:

.mydiv {
    positon: absolute;
    left: 100px;
}

Tablet CSS:

@media (max-width:768px){
    .mydiv {
        left: 0;
        right: 0;
    }
}

I could do something like right: 400px to get it to the position that I want but I am just curious if there is a way where I can use right: 0 so I know for sure that it is pushed totally to the right.

Thanks!

Bizarre answered 25/9, 2016 at 2:42 Comment(0)
A
12

To reset the left property use

left: auto;

You can use CSS reference to get initial values of CSS properties. For example here is the reference for the left property: https://developer.mozilla.org/en/docs/Web/CSS/left

Afroasiatic answered 25/9, 2016 at 2:46 Comment(0)
M
1

When you want to shift an absolutely positioned element all the way to the other side use 100%.

In other words, you don't need to reset left or use right. Just override left:

@media (max-width:768px){
    .mydiv {
        left: 100%;
    }
}

And for perfect positioning, you may need this:

@media (max-width:768px){
    .mydiv {
        left: 100%;
        transform: translateX(-100%);
    }
}

Since left: 100% will align the element 100% to the other side of the container based on the element's left edge, this may cause the element to disappear past the right edge of the container.

The transform rule tells the element to slide itself back exactly 100% of its own width. More details here: Element will not stay centered, especially when re-sizing screen

Malynda answered 25/9, 2016 at 3:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.