简体   繁体   中英

Place the right side of a <div> to left of window

I am trying to implement an Android-style sidebar in HTML/CSS, which shows and hides itself. Now, I am stuck fiddling with right and left properties in CSS trying to figure out (admittedly not very well worded in the title) how to place the div (sidebar) just the right amount to the left so that it is completely hidden.

An example:

+---+--------------+
|   |              |
| D |       B      |
|   |              |
+---+--------------+

(where D is the <div> in question and B is the actual displayed area on the screen)

Is this possible? I've tried right: 100% , which essentially does what I want, but it doesn't work with transition as it can't transition from right: 100%; left: auto right: 100%; left: auto , to right: auto; left: 0 right: auto; left: 0 (or at least in my experience)...

Help is well appreciated!

EDIT: I realise that I could have a constant-width sidebar and therefore be able to easily transition that, but I would like to have a sidebar where the width is not predetermined (evidence seems to point to JavaScript as the only option in order to access the element's width)

Have you considered the fact that you can put negative values into margins?
For example, if your div was 50px wide:

margin-left: -50px;

You could then use the transition to add 50px to the left margin on an event.

If the div is a set width in viewport units you can subtract half of its width from 50vw to place it in the center after hiding it with a negative margin.

body{
  margin:0px;
  padding:0px;
}

div{
  background:gray;
  height:75vh;
  width:25vw;
  margin-left:37.5vw; /*50-(25/2) ensures it is centered*/
  animation:slide 2s;
}

@keyframes slide{
  from {margin-left:-25vw;}
  to {margin-left:37.5vw;}
}

I found that I had to use JavaScript for this problem, as it seems impossible to do with CSS. So, the element's original position would be:

right: 100%;

And I can use:

el.style.right = "calc(100% - " + el.offsetWidth);

...When active. Or -webkit-transform .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM