首页 > 解决方案 > CSS - 堆叠元素在较小的屏幕上相互溢出

问题描述

我有一列元素,每个元素都低于前一个元素。我的代码的简化版本如下所示:

<div style="position: relative; height: 100%;">
   <div style="position: absolute;">Really long text here</div>
   <div style="position: absolute;">Not so long text here</div>
</div>

基本上,我的问题是,在较小的屏幕尺寸上,第一个内部 div 会溢出并进入第二个 div 的内容,并且来自两个 div 的文本将彼此重叠。

我怎样才能防止这种情况?我希望完整显示我的文本,但不允许它溢出到其相邻的 div 中。

标签: htmlcsstextoverflow

解决方案


<head>    
 <style>
  #mainBox{
   display: flex;
   flex-wrap: wrap;
   justify-content: space-around;
  }
  #mainBox #box1{
   order: 1;
   align-self: flex-start;
   flex-basis: 60%; /*this is the width you wish the div to take*/
  }
  #mainBox #box2{
   order: 2;
   align-self: flex-start;
   flex-basis: 30%;
  }

  /*for smaller screens*/
  @media screen and (max-width: 520px){
    #mainBox{
    display: flex;
    flex-wrap: nowrap;
    flex-direction: column;
   }
  }
 </style>
</head>
<body>
 <div id="firstBox" style="position: relative; height: auto;">
  <div id="box1">Really long text here</div>
  <div id="box2">Not so long text here</div>
 </div>
</body>

有了这个,你将有一个响应式布局flexbox,上面有很多属性,它的 2018 现在很多浏览器都支持它,它将为你节省很多时间。


推荐阅读