居中对齐一个固定位置的div [英] center aligning a fixed position div

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

问题描述

我正在尝试获取一个 position:fixed 在我的页面上居中对齐的 div.

I'm trying to get a div that has position:fixed center aligned on my page.

我总是能够使用这个hack"用绝对定位的 div 来做到这一点

I've always been able to do it with absolutely positioned divs using this "hack"

left: 50%; width: 400px; margin-left:-200px

...其中 margin-left 的值是 div 宽度的一半.

...where the value for margin-left is half the width of the div.

这似乎不适用于固定位置的 div,相反,它只是将它们的最左角放置在 50% 处,并忽略了 margin-left 声明.

This doesn't seem to work for fixed position divs, instead it just places them with their left-most corner at 50% and ignores the margin-left declaration.

关于如何解决这个问题以便我可以居中对齐固定定位元素的任何想法?

Any ideas of how to fix this so I can center align fixed positioned elements?

如果你能告诉我一种比我上面概述的方法更好的居中对齐绝对定位元素的方法,我会奖励 M&M.

And I'll throw in a bonus M&M if you can tell me a better way to center align absolutely positioned elements than the way I've outlined above.

推荐答案

Koen 的回答并没有完全将元素居中.

Koen's answer doesn't exactly centers the element.

正确的方法是使用CCS3 transform 属性.尽管它某些旧浏览器不支持.而且我们甚至不需要设置固定或相对的width.

The proper way is to use CCS3 transform property. Although it's not supported in some old browsers. And we don't even need to set a fixed or relative width.

.centered {
    position: fixed;
    left: 50%;
    transform: translate(-50%, 0);
}

工作 jsfiddle 比较这里.

Working jsfiddle comparison here.

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

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