[英]How to keep div in the center of viewport
I am creating a feedback system for one of my projects. 我正在为我的一个项目创建一个反馈系统。 My target device is iPad.
我的目标设备是iPad。 Basically what happens is a div called into the page via ajax and it is supposed to overlay the content underneath.
基本上会发生一个通过ajax调用div的div,它应该覆盖下面的内容。 I have that part working.
我有那部分工作。
What I want to do is have the div locked to the middle of the view-port. 我想做的是将div锁定到视口的中间。 I have tried
position:fixed
on my element which works, except it will lock into the wrong position. 我已经尝试了
position:fixed
在可以正常工作的元素上,但是它将锁定在错误的位置。 It seems to be centering itself to the initial position of the viewport. 它似乎将自身居中到视口的初始位置。 If I scroll down to the bottom of a longer page and call my feedback window, it will still be near the top.
如果我向下滚动到较长页面的底部并调用我的反馈窗口,则该窗口仍将位于顶部附近。
$(document).ready(function(){
$(".popup").css({
top: "50%",
left: "50%",
marginLeft: -$(".popup").width() / 2,
marginTop: -$(".popup").height() / 2
});
});
If I can find the top of the viewport I think I'd be able to get this working right. 如果我能找到视口的顶部,我想我可以使它正常工作。
I've looked into: http://www.appelsiini.net/projects/viewport but it doesn't really solve my problem. 我调查了: http : //www.appelsiini.net/projects/viewport,但这并不能真正解决我的问题。
Any help, advice or pointers in the right direction would be greatly appreciated! 任何帮助,建议或正确方向的指导将不胜感激! Thanks!
谢谢!
Fixed positioning is applied relative to the top-left corner of the window, regardless of how far down you're scrolled (which I assume is what you want). 固定位置是相对于窗口的左上角应用的, 而不管您滚动了多深 (我认为这是您想要的)。
So: 所以:
.popup {
position:fixed;
top:20px;
left:40px;
right:40px;
}
Will, first of all, put your popup 20px from the address bar (meaning, even if you scrolled to the bottom). 首先,请从地址栏中输入20像素的弹出窗口(这意味着即使您滚动到底部)。
Next, setting both left
AND right
will "stretch" the fixed element to start and end 40px (or whatever you give it) from both sides of the window. 接下来,同时设置
left
和right
将“固定”固定元素从窗口的两侧开始和结束40px(或您指定的大小)。 That's a convenient way of centering this popup div. 这是居中此弹出div的便捷方法。
If your popup needs to be a fixed size – not stretched based on the width of the window – you could set both the left and right (to zero probably) and then inside this div, have another div with margin:0 auto
, which will center that inner div within the fixed outer div. 如果您的弹出窗口需要固定大小-而不是根据窗口的宽度进行拉伸-您可以将左右两边(可能设置为零),然后在该div内设置另一个带有
margin:0 auto
div。使该内部div在固定外部div内居中。
PS Just as you can set both left
and right
, you can also set both top
and bottom
, which will have corresponding results. PS正如你可以同时设置
left
和right
,你还可以设置两个top
和bottom
,这将有相应的结果。 However, if you need a fixed height, you won't be able to vertically center it using the margin:auto
trick. 但是,如果您需要固定的高度,则无法使用
margin:auto
技巧垂直将其居中。
不知道是不是这种情况,但是如果$(".popup")
最初被display:none
隐藏,那么它的宽度和高度在页面加载时将为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.