3
<html>
<head>
<style type="text/css" rel="stylesheet">
    * {margin:0;padding:0;}

    div#box {background-color:green;width:1000px;}

    /* #box {position:absolute;top:0;right:0;} */
    /* #box {position:absolute;top:0;left:0;} */
    /* #box {float:right;} */
    #box {float:left;}

    .clearer {clear:both;}
</style>
</head>
<body>
    <div id="box">
        asdafdsf
    </div>
    <div class="clearer"></div>
</body>
</html>

取消注释第一个浮动左侧 id 与浮动右侧,你会看到。我也将我尝试过的解决方案注释掉了。

您应该从复制和粘贴中获得完整的复制。

4

3 回答 3

2

如果不使用 javascript,我不相信有任何方法可以解决这个问题。浏览器相对于该页面的左上角呈现页面,因此位于该 0,0 点上方或左侧的任何内容实际上都在屏幕外。所有溢出都发生在底部和右侧。这与任何块元素内部的内容相同。因此,如果您有一个相对于页面右侧定位的项目,宽度超过 100%。0,0 原点左侧的部分将简单地在屏幕外。

不过,我希望有人能证明我错了。

这是一个有效的javascript解决方案:

<html>
<head>
<style type="text/css" rel="stylesheet">
    * {margin:0;padding:0;}
    div#box {background-color:green;width:1000px;}
    #box {position:absolute;top:0;left:0;}
    .clearer {clear:both;}
</style>
</head>
<body>
    <div id="box">
        asdafdsf
    </div>
    <div class="clearer"></div>
    <script type="text/javascript">
        function layout() {
            if( typeof( window.innerWidth ) == 'number' )
                this.screenWidth = window.innerWidth;   
            else //patch for IE
                this.screenWidth = document.body.clientWidth;
            this.el = document.getElementById('box')
            if (this.el.offsetWidth > this.screenWidth)
                window.scroll(this.el.offsetWidth,0);
            else
                this.el.style.left = (this.screenWidth - this.el.offsetWidth) + 'px';
        }
        function eventListener(el,action,func) {
            if (el) {
                if (el.addEventListener)
                    el.addEventListener(action, func, false);
                else if (el.attachEvent)
                    el.attachEvent('on' + action, func);
            }
        }
        eventListener(window,'resize',layout);
        layout();        
    </script>
</body>
</html>
于 2009-10-27T23:35:40.563 回答
0

我有(我认为可能是)一个类似的问题,我想右对齐一个比包含它的 div 更宽的画布元素。div 大约 300px,canvas 元素大约 1000px。

使用float: right,画布右对齐,但 div 上的滚动条消失了。

我使用 jQuery 解决了这个问题,使用scrollLeft()基于 div 和画布宽度设置初始滚动,类似于:

$("#div").scrollLeft(canvas.width() - div.width() )
于 2015-03-31T01:23:10.090 回答
0

我有这个问题。我通过使内部内容显示:inline-block,然后是外部容器 text-align:right 来解决它。内部内容会向右“浮动”(就好像它是内联文本一样),但滚动条仍然存在。您必须在内部内容上重置 text-align ,否则它的所有内容也会正确对齐。

如果您的内部内容不喜欢被内联块,那么您就会被其他解决方案所困。

于 2020-10-20T16:31:21.343 回答