[英]How can I center an element in the middle of the viewport?
I want to center an element (div, modal/dialog box) in the middle of the viewport, regardless of the page size.无论页面大小如何,我都想将元素(div、模态/对话框)居中放置在视口的中间。
The idea is that the dialog box always appears in the middle of the current view port, so it can be seen by a user regardless of the page size.这个想法是对话框总是出现在当前视口的中间,因此无论页面大小如何,用户都可以看到它。 In my case, I have a very long page with lots of scrolling and if the user is at the bottom of the page and the dialog box appears in the middle of the page it cannot be seen by the user because it is not in his viewport.
在我的情况下,我有一个很长的页面,有很多滚动,如果用户在页面底部并且对话框出现在页面中间,用户将无法看到它,因为它不在他的视口中.
My HTML site is run in an iframe, which makes the task even more difficult.我的 HTML 站点在 iframe 中运行,这使得任务更加困难。
How can I do that with CSS only?我怎么能只用 CSS 做到这一点?
Apply following CSS应用以下 CSS
.center{
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
Position fixed would make sure it's relative to the viewport.位置固定将确保它相对于视口。 left and top 50% would move the element's top and left to the center.
left 和 top 50% 会将元素的顶部和左侧移动到中心。 You'd want it to be in the absolute center, it can be done by transform: translate(-50%,-50%);
您希望它位于绝对中心,可以通过转换完成: translate(-50%,-50%);
Try this snippet.试试这个片段。
.modal{ width: 200px; height: 150px; border: 1px solid black; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
<div class="modal"> </div>
Well, after you edited the question and mentioned, that the page is in an iframe
, I can at least say, that it is not possible to place an element inside of an iframe
to the current viewport of the browser.好吧,在您编辑问题并提到页面位于
iframe
,我至少可以说,不可能将iframe
内的元素放置到浏览器的当前视口。 The most global context of the element is the iframe
itself, and it has no information about in whatever it is embedded.元素最全局的上下文是
iframe
本身,它没有关于它嵌入的任何信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.