CSS:根据屏幕宽度将float:left元素居中? [英] CSS: Center a float:left element based on screen width?

查看:46
本文介绍了CSS:根据屏幕宽度将float:left元素居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用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.

如果是后者,请不要使用浮点...从设置 width:auto; 开始(我认为应该使其自动扩展以适合内容).然后,您将需要一些JavaScript来测量DIV的宽度,设置 width: css属性(以像素为单位),然后测量浏览器窗口,并根据这些测量值使容器居中.

If the latter, don't use a float...start by setting width:auto; (I think that should make it auto-expand to fit content). Then you will need some javascript to measure the width of the DIV, set the width: css property in pixels, then measure the browser window, and center the container based on these measurements.

对不起,我对width:auto;错了.我猜只是将其浮动,然后使用如上所述的javascript手动设置margin-right和margin-left.

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元素居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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