[英]How to position the element using absolute position?
我正在尝试为我的应用程序创建一个响应式设计。
我的背景图片很大,当用户使用大屏幕时它将显示完整尺寸,如果用户使用小屏幕则只能显示部分尺寸。
我想在应用程序中的绝对位置上放置几个元素,但问题是我无法锁定它们的上下值,因为屏幕尺寸发生了变化。
我有类似的东西
CSS
#background{
background: url('BG.jpg') no-repeat top center fixed;
width: 1900px;
height: 1200px;
}
#element{
position: fixed;
z-index: 5;
top: 50%; //looks fine in 1900 x 1200 screen but position is off on 1200 x 1000
left:70%; //looks fine in 1900 x 1200 screen but position is off on 1200 x 1000
}
HTML
<div id='background'></div>
<img id='element' src='test.jpg' />
当用户的屏幕较小时,如何将元素的位置保持在同一位置? 谢谢您的帮助!
使用position: absolute
,您需要确保其父对象的position
属性不是默认属性(是static
)。 如果没有这样的父母,则该文档为有效父母。 对于您的示例,我建议像这样将img#element设为div#background的子级
<div id='background'>
<img id='element' src='test.jpg' />
</div>
然后添加position:relative;
到#background CSS样式
#background{
background: url('BG.jpg') no-repeat top center fixed;
width: 1900px;
height: 1200px;
position: relative;
}
使用relative
的原因是因为它不会将元素从文档流中移出(就像fixed
或absolute
那样),并且只要您不为该元素指定top
, left
,'bottom'或right
属性即可父对象(在这种情况下为#background
),它将与默认位置保持在同一位置。
我认为这对您来说不是开箱即用的。 您需要弄清楚如何使图像的宽度也动态化。 您可以为其指定基于百分比的宽度,也可以使用媒体查询。
Ia也刚刚注意到您的position:fixed
为img#element
。 将其更改为position:absolute
。 这样就可以相对于position:relative
parent而不是window进行定位。
考虑制作一个可计算屏幕宽度的javascript函数。 之后,在#background处添加等于(屏幕宽度/ -2)的左边距。 使#background宽度和高度-100%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.