简体   繁体   English

将右侧的 <div> 窗口左边

[英]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. 我正在尝试在HTML / CSS中实现一个Android样式的侧边栏,该边栏可显示和隐藏自身。 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. 现在,我一直在摆弄CSS的rightleft属性,试图弄清楚(标题中的措辞不太好)如何将div(侧边栏)恰好位于左侧,以便完全隐藏。

An example: 一个例子:

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

(where D is the <div> in question and B is the actual displayed area on the screen) (其中D是所讨论的<div>B是屏幕上实际显示的区域)

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% ,基本上可以完成我想要的操作,但是它不能与transition因为它无法从right: 100%; left: auto过渡right: 100%; left: auto right: 100%; left: auto , to right: auto; left: 0 right: 100%; left: autoright: auto; left: 0 right: auto; left: 0 (or at least in my experience)... right: auto; left: 0 (或至少以我的经验)...

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) 编辑:我意识到我可以有一个恒定宽度的侧边栏,因此能够轻松地转换它,但是我想拥有一个宽度未预先确定的侧边栏(证据似乎指向JavaScript作为唯一的选择,以便访问元素的宽度)

Have you considered the fact that you can put negative values into margins? 您是否考虑过可以将负值添加到边距中的事实?
For example, if your div was 50px wide: 例如,如果您的div宽度为50px

margin-left: -50px;

You could then use the transition to add 50px to the left margin on an event. 然后,您可以使用过渡功能将50px添加到事件的左边距。

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. 如果div是以视口单位为单位的设置宽度,则可以将其负宽度隐藏后,从50vw中减去其宽度的一半,以将其放置在中心。

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. 我发现我必须使用JavaScript来解决这个问题,因为与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 . -webkit-transform

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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