Подтвердить что ты не робот

Как установить позицию DIV на 200 пикселей слева от центра

Я хочу разместить DIV 200 пикселей слева от центра.

В настоящее время я использую следующий код, но на дисплеях с более высоким разрешением (например, 1920 × 1080) DIV выскользнул из положения:

.hsonuc {
    position: absolute;  
    top: 20px; 
    margin:auto;
    margin-left:200px;
    display:none;
}

Что я хочу достичь:

Illustrating a div that is positioned 200px to the left of the center of the page

4b9b3361

Ответ 1

Просто расположите его 50% справа (right:50%;), а затем нажмите его, используя margin-right:200px; (пример).

HTML

<div class="hsonuc">DIV</div>

CSS

.hsonuc {
    position:absolute;
    top:20px;
    right:50%; /* Positions 50% from right (right edge will be at center) */
    margin-right:200px; /* Positions 200px to the left of center */
}

Ответ 2

Вы также можете использовать Javascript для определения количества пикселей с левой стороны браузера 200px от центра на самом деле. Таким образом, вам не нужно использовать position: absolute.

example (jQuery):

var centerMark = Math.round( $(window).width() / 2 ); //define the center of the screen
var elementWidth = $('.hsonuc').width();
var position = centerMark - 200 - elementWidth; //define where 200 left of the center is and subtract the width of the element.

//now you have `position` you can use it almost any way you like.
//I prefer to use margins, but that all up to you.

$('.hsonuc').css('margin-left', position);

Ответ 3

вы можете использовать комбинацию% и px; Если ваша ширина div равна 300px, то половина div равна 150px. 150 + 200 = 350 пикселей;  затем используйте это

margin-left:calc(50% - 350px);