CSS: center float: left element based on screen width?

I need to use a float div (the main window of my application), and I would like to focus it on a DIV based on the client screen width. How can i do this?

Now I use the left: 20%, but not always centered depending on the user's screen resolution

+2
source share
3 answers

Do you want the div to grow relative to the browser window, or to fit the contents inside it?

If the former, you can just use the percentage width, not the pixel, and it should stay in the center.

, float... start, width:auto; ( , , ). javascript DIV, width: css , .

, : auto;. , , javascript, , margin-right margin-left.


, .

#float { 
    float:left;
    margin-left:50%;
    position:relative;
}

, jquery,

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

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

, javascript ... , JS noob:)

+3

.mainWindow {
    margin: 0 auto;
}

, text-align: center;

0

Usually I use a container with an autocentered container, and then put any other containers into this container (for example, your floating div). Is there any special reason why you cannot do this?

CSS example:

#container {
width: 960px;
margin: 0 auto;
position: relative;
}
0
source

Source: https://habr.com/ru/post/1737773/


All Articles