首页 > 解决方案 > 当屏幕宽度变小时,绝对定位的 Div 会离开屏幕

问题描述

我现在正在为我的投资组合制作一个这样的网站。链接
当您水平减小屏幕尺寸时,包含人物图像的框不会离开屏幕,但我的会。有没有办法防止这种情况并使其像示例网站一样?

另一个问题是我发现当屏幕宽度小于 900px 时,主框下方会创建一个巨大的空白区域。我不知道它为什么会发生以及如何解决它。

我的网站

HomeMain.js

export class HomeMain extends Component {
  render() {
    return (
      <>
        <div className="main-box">
          <div className="left-main-box"></div>
          <div className="right-main-box"></div>
          <CenterBox />
        </div>
      </>
    );
  }
}

中心框.js


export class CenterBox extends Component {
  render() {
    return (
      <div className="main-center-box">
        <div className="left-center-box">left-center</div>
        <div className="right-center-box">right-center</div>
      </div>
    );
  }
}

应用程序.scss

/* Homepage Style */

.main-box {
  height: $main-container-height;
  position: relative;

  .left-main-box {
    height: $main-container-height;
    width: 45%;
    min-width: 400px;
    display: inline-block;
    background-color: #ede7dd;
  }

  .right-main-box {
    display: inline-block;
    height: $main-container-height;
    width: 55%;
    background-color: white;
  }
}

/* Homepage center box style */

.main-center-box {
  position: absolute;
  width: 800px;
  top: 50%;
  left: 50%;

  transform: translate(-50%, -50%);

  .left-center-box {
    background-color: #faf7f4;
    display: inline-block;
    width: 50%;
    height: 550px;
  }
  .right-center-box {
    background-color: white;
    display: inline-block;
    width: 50%;
    height: 550px;
  }
}

标签: cssreactjs

解决方案


在示例网站中保存图像的元素不像您那样绝对居中。相反,应用的是相对于视口宽度计算的边距:

    margin: 72px 0px 44px calc((100% - 980px) * 0.5);

第四个边距值是通过使用calc()( Docs ) 来表达一个公式来设置的,该公式基本上将左边距设置为在大型设备上越来越高的值,同时0在低于 980 像素宽度的显示器上返回。

至于第二个问题:.left-main-box占用最小 400px 宽度,并且它的.right-main-box右边只是在小屏幕上换行。通过计算宽度,如:

.right-main-box {
  width: min(calc(100% - 400px), 55%);
}

你得到所需的间距。


推荐阅读