允许绝对容器宽度溢出屏幕宽度

Allow absolute container width to overflow screen width

我有一个绝对位于屏幕右下角的容器。

widthheight 设置为自动。

容器内是元素,这些元素设置为 inline-block。想象一下 facebook 的聊天 windows 弹出窗口,这正是我所拥有的。

当我添加元素时,它按预期工作,在屏幕右侧并排显示。问题是,当我添加足够多时,容器达到屏幕的宽度,它们就会换行。而不是继续离开屏幕。

我怎样才能做到这一点?

<div class='container'>
    <div class='element'></div> 
    <!-- Adding too many of these will cause them to wrap
     above each other instead of flowing off the left side of the screen --> 
</div>

.container{
    position: absolute;
    right: 0:
    bottom: 0;
    width: auto;
    height: auto;
}

.element{
    width: 300px;
    height: 500px;
}

我们的想法是让您的 element 成为 inline-block,然后使用 white-space: nowrap 属性 将它们强制排成一行 - 请参见下面的演示:

.container{
    position: absolute;
    right: 0;
    bottom: 0;
    width: auto;
    height: auto;
    white-space: nowrap;
}

.element{
    width: 300px;
    height: 500px;
    display: inline-block;
    border: 1px solid red;
}
<div class='container'>
    <div class='element'>element 1</div> 
    <div class='element'>element 2</div> 
    <div class='element'>element 3</div> 
    <div class='element'>element 4</div> 
</div>

如果您想将 element 的方向设置为从右到左,您可以使用 scale transform 的巧妙技巧 - 请参见下面的演示:

.container{
    position: absolute;
    right: 0;
    bottom: 0;
    width: auto;
    height: auto;
    white-space: nowrap;
    transform: scaleX(-1);
}

.element{
    width: 300px;
    height: 500px;
    display: inline-block;
    border: 1px solid red;
    transform: scaleX(-1);
}
<div class='container'>
    <div class='element'>element 1</div> 
    <div class='element'>element 2</div> 
    <div class='element'>element 3</div> 
    <div class='element'>element 4</div> 
</div>

Flexbox 的一个不错的 属性:带有 flex-wrap: nowrap(这是默认值):弹性容器不允许其弹性项目占据 2+ 行并会迫使它们溢出容器,即使它们的宽度之和比它们的父项大得多。
并且从右到左显示它们,在左侧的视口之外,就像 flex-direction: row-reverse.
一样简单 优于 inline-block:项目之间没有 whitespace/gap(通常为 4px)

.container{
    position: absolute;
      right: 0;
      bottom: 0;
    display: flex;
      flex-direction: row-reverse;
    width: auto;
    height: auto;
}

.element{
    width: 300px;
    height: 200px;
    /* flex: 0 0 300px; not needed */
    border: 1px solid red;
}
<div class='container'>
    <div class='element'>element 1</div> 
    <div class='element'>element 2</div> 
    <div class='element'>element 3</div> 
    <div class='element'>element 4</div> 
</div>