【问题标题】:how to set DIV position to 200 pixels to left of the center如何将DIV位置设置为中心左侧200像素
【发布时间】:2012-06-23 00:52:00
【问题描述】:

我想将DIV 定位在中心左侧 200 像素处。

我目前正在使用以下代码,但在更高分辨率的显示器(例如 1920×1080)上,DIV 滑出位置:

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

我想要达到的目标:

【问题讨论】:

    标签: css positioning center


    【解决方案1】:

    只需将其从右侧定位到 50% (right:50%;),然后使用 margin-right:200px; (example) 将其推过去。

    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】:

      您可以使用 % 和 px 的组合; 如果你的 div 宽度是 300px,那么 div 的一半是 150px。 150 + 200 = 350 像素; 然后用这个

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

      【讨论】:

        【解决方案3】:

        您还可以使用 Javascript 来确定距浏览器左侧 200 像素中心实际有多少像素。这样你就不必使用position: absolute

        示例(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);
        

        【讨论】:

        • 其实这是不正确的。这会将元素的 left 边缘定位在中心左侧 200px 处,而不是元素的 right 边缘。此外,您必须计算元素的大小并从position 中减去。
        • @bfrohs 你是对的。我误读了这个问题。我正在编辑我的答案。
        猜你喜欢
        • 2023-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多