CSS: Center a float:left element based on screen width?

0

Issue

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?

Right now I’m using a left:20% but that’s not always centered depending on the user’s screen resolution

Solution

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.

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.

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;
}

And then, using jquery,

$(document).ready(function() {
    var float_width = $('#float').width();
    var left_spacing = float_width / 2;

    $('#float').css('left', '-' + left_spacing);
});

Forgive me if my javascript is off or doesn’t quite work…I didn’t test it and I’m a JS noob 🙂

Answered By – Kevin C.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More