问题描述
我必须使用float div(我的应用程序的主窗口),并且我想根据客户端的屏幕宽度居中放置浮动DIV.我该怎么办?
I have to use a float div (the main window of my application), and I'd like to center that floated DIV based on the client's screen width. How can I accomplish that?
现在我使用的是left:20%,但这并不总是居中,具体取决于用户的屏幕分辨率
Right now I'm using a left:20% but that's not always centered depending on the user's screen resolution
推荐答案
您是要使div相对于浏览器窗口增大,还是要使其内容适合浏览器窗口?
Do you want the div to grow relative to the browser window, or to fit the content inside of it?
如果是前者,则可以仅使用基于百分比的宽度而不是像素,并且该宽度仍应居中.
If the former, you can just use a percentage based width rather than pixel, and it should still center.
Sorry, I was wrong about width:auto;. I guess just float it, and then use javascript like I described above to manually set the margin-right and margin-left.
对不起,想出一个更好的解决方案.
Sorry, thought up a better solution.
#float {
float:left;
margin-left:50%;
position:relative;
}
然后使用jquery
And then, using jquery,
$(document).ready(function() {
var float_width = $('#float').width();
var left_spacing = float_width / 2;
$('#float').css('left', '-' + left_spacing);
});
请原谅我,如果我的JavaScript关闭或运行不正常...我没有对其进行测试,并且我是JS noob:)
Forgive me if my javascript is off or doesn't quite work...I didn't test it and I'm a JS noob :)
这篇关于CSS:根据屏幕宽度将float:left元素居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!