Align fixed elements to screen on mobile?

时间:2016-04-15 11:08:56

标签: javascript jquery html css css-position

Fixed elements are aligned perfectly on desktop (bottom and right are aligned to the browser window). But on mobile the elements are aligned to the container size.

This is how it look on mobile (the black line represent the screen):

enter image description here

This is how I want it to look on mobile (the black line represent the screen):

enter image description here

Example code (In my real life application the canvas need to be larger than the viewport (hence the 150vh and 150vw size of the canvas)):

html

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</head>

<body>
  <div class="container">
    <div class="fixedElement">I AM A FIXED ELEMENT</div>
    <div class="fixedElement2">I AM A FIXED ELEMENT 2</div>
  </div>
</body>

css

body {
  margin: 0;
}

.container {
  width: 150vw;
  height: 150vh;
  background-color: orange;
}

.fixedElement {
  position: fixed;
  top: 50px;
  right: 200px;
}

.fixedElement2 {
  position: fixed;
  bottom: 50px;
  left: 200px;
}

Codepen example

Any suggestions on how to fix this?

3 个答案:

答案 0 :(得分:0)

.container {
  width: 100vw;
  height: 100vh;
}

html,body,.container{
   height:100%;
   width:100%;
}

答案 1 :(得分:0)

只需将以下规则添加到正文的css中:

body {
   width: 100vw;
}

我创建了一个适合我的codepen示例:Example on Codepen

我希望这就是你搜索的内容。

答案 2 :(得分:0)

你在那里混合单位(vw和px)。

vw单位相对于视口的宽度。将此值设置为150vw会使您的“画布”(具有类container的div容器)的宽度达到150%。它将身体或视口向右延伸50%。

将固定元素位置值设置为固定单位right: 200px可能在某些视口中有效,但确实不够。视口越宽,容器越宽(150vw),但200px将始终相同。