【问题标题】:Div Module Left and Right Margin Not Working in Responsive DesignDiv 模块左右边距在响应式设计中不起作用
【发布时间】:2021-02-12 16:33:04
【问题描述】:

我有一个 div 模块,当您单击按钮时会显示该模块。我正在努力实现:

  • 当视口超过 786 像素时,制作一个最大宽度为 786 像素的 div“模块”AND 和中心 div“模块”
  • 当视口小于 786px 时,div“模块”占用 100% 宽度,但保留 32px 左右边距作为呼吸空间

我无法完成后者,我不知道为什么。左边距和右边距没有按预期工作,除了只有左边距应用并将 div“模块”推离屏幕。

.module {
    display: block;
    position: absolute;
    width: 100%;
    max-width: 768px;
    background-color: yellow;
    z-index: 100;
    right: 0;
    left: 0;
    margin: auto;
}

.overlay {
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    opacity: 0.5;
    background-color: Gray;
}

@media screen and (max-width: 768px) {
  .module {
  margin-left: 32px;
  margin-right: 32px;
  // I assume the value 'auto' this resets the following property
  top: auto;
  left: auto;
 }
}
<div class="content">
  <button>Open Module</button>
</div>

<div class="module"></div>

<div class="overlay"></div>

【问题讨论】:

  • 768下加width: calc( 100% - 64px );为什么?因为宽度 100% + 64 边距... = 你所拥有的。

标签: html css sass


【解决方案1】:

试试这个

.module {
    display: block;
    position: relative;
    max-width: 768px;
    height: 200px;
    background-color: yellow;
    z-index: 100;
    margin: auto;
}

.overlay {
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    opacity: 0.5;
    background-color: Gray;
}

@media screen and (max-width: 768px) {
  .module {
  margin-left: 32px;
  margin-right: 32px;
  // I assume the value 'auto' this resets the following property
  top: auto;
  left: auto;
 }
}

这是 jsfiddle 示例的链接:

https://jsfiddle.net/LaKhDaR/auewovfr/44/

【讨论】:

    【解决方案2】:

    您只需要删除模块 CSS 上的 width:100% ,因为宽度会随着屏幕变小而改变。

    同时删除该行

    /*top: auto;
     left: auto; It will just initialize your absolute position*/ 
    

    .module {
        display: block;
        position: absolute;
        /*width: 100%;*/
        height: 100px;
        max-width: 768px;
        background-color: yellow;
        z-index: 100;
        right: 0;
        left: 0;
        margin: auto;
    }
    
    .overlay {
        display: block;
        position: fixed;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        opacity: 0.5;
        background-color: Gray;
    }
    
    @media screen and (max-width: 768px) {
      .module {
      margin-left: 32px;
      margin-right: 32px;
      /*top: auto;
      left: auto; It will just recreate 
     }
    }
    <div class="content">
      <button>Open Module</button>
    </div>
    
    <div class="module"></div>
    
    <div class="overlay"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多