CSS 如何将 DIV 位置设置为中心左侧 200 像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11127120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set DIV position to 200 pixels to left of the center
提问by Haluk üNAL
I want to position a DIV
200 pixels to left of the center.
我想DIV
在中心左侧放置 200 像素。
I am currently using the following code, but on higher resolution displays (e.g. 1920×1080), the DIV
was slipping out of position:
我目前正在使用以下代码,但在更高分辨率的显示器(例如 1920×1080)上,它DIV
正在滑出位置:
.hsonuc {
position: absolute;
top: 20px;
margin:auto;
margin-left:200px;
display:none;
}
What I want to achieve:
我想要达到的目标:
回答by 0b10011
Simply position it 50%
from the right (right:50%;
), and then push it over using margin-right:200px;
(example).
只需将其50%
从右侧 ( right:50%;
) 定位,然后使用margin-right:200px;
(示例)将其推过去。
HTML
HTML
<div class="hsonuc">DIV</div>
CSS
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 */
}
回答by Haluk üNAL
you can use combination of % and px; If your div width is 300px, than half of the div is 150px. 150 + 200 = 350px; then use this
您可以使用 % 和 px 的组合;如果你的 div 宽度是 300px,那么 div 的一半是 150px。150 + 200 = 350 像素;然后用这个
margin-left:calc(50% - 350px);
回答by LuudJacobs
You could also use Javascript to determine how many pixels from the lefthand side of the browser 200px from the center actually is. That way you don't have to use position: absolute
.
您还可以使用 Javascript 来确定距中心 200 像素的浏览器左侧实际有多少像素。这样你就不必使用position: absolute
.
example (jQuery):
示例(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's all up to you.
$('.hsonuc').css('margin-left', position);