居中位置:固定元素 [英] Center a position:fixed element

查看:205
本文介绍了居中位置:固定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个 position:fixed; 弹出框以屏幕动态宽度和高度为中心。我使用 margin:5%auto; 。没有 position:fixed; 它水平居中,但不垂直。

I would like to make a position: fixed; popup box centered to the screen with a dynamic width and height. I used margin: 5% auto; for this. Without position: fixed; it centers fine horizontally, but not vertically. After adding position: fixed;, it's even not centering horizontally.

这是完整的集合:

.jqbox_innerhtml {
    position: fixed;
    width: 500px;
    height: 200px;
    margin: 5% auto;
    padding: 10px;
    border: 5px solid #ccc;
    background-color: #fff;
}

<div class="jqbox_innerhtml">
    This should be inside a horizontally
    and vertically centered box.
</div>

如何在CSS中将此框置于屏幕中?

How do I center this box in screen with CSS?

推荐答案

您基本上需要设置顶部 50%以div的左上角为中心。您还需要将 margin-top margin-left 设置为div的高度和宽度的负的一半

You basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.

因此,提供<!DOCTYPE html> 模式),这应该:

Thus, provided a <!DOCTYPE html> (standards mode), this should do:

position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */

或者,如果你不关心垂直和旧的浏览器如IE6 / 7 ,那么您也可以向具有 left:0 和 right:0 > $ > ,使得固定定位的元素具有固定宽度知道它的左和右偏移在哪里开始。在您的情况下:

Or, if you don't care about centering vertically and old browsers such as IE6/7, then you can instead also add left: 0 and right: 0 to the element having a margin-left and margin-right of auto, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:

position: fixed;
width: 500px;
height: 200px;
margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */
left: 0;
right: 0;

同样,这只能在IE8 +中使用,如果你关心IE,它只是水平不垂直。

Again, this works only in IE8+ if you care about IE, and this centers only horizontally not vertically.

这篇关于居中位置:固定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆