使容器内响应 div 正确

Make right div within container responsive

我在一个容器中有 2 个 div,一个在中间,一个在右边。我希望右侧 div 的宽度 响应 。目前,只有居中的 max-width 有效。

看到这个 jsFiddle

如何让右边的 div 也响应?

HTML:

<div id="container">

    <div id="middle">Centered</div>

    <div id="right">Make me responsive</div>

</div>

CSS:

#container {
    width: 100%;
    text-align: center;
    position: relative;
}

#middle {
    background: #ddd;
    margin: 0 auto;
    position: relative;
    width: 100%;
    max-width:300px;
    height:300px;
    display: inline-block;
    vertical-align: top;
}

#right {
    background:yellow;
    width:100%;
    max-width:300px;
    display: inline-block;
    vertical-align: top;
    position: absolute;
}


@media screen and (max-width: 350px) {
    #right {
        display: none;
    }
}

您可以通过执行以下操作来完成您想要的:JSFiddle
唯一的问题是你的中间 div 必须有一个固定的宽度,但是使用媒体查询你可以忘记这一点。请记住 calc browser support could be better (although there are polyfills).

#middle {
    position: relative;
    margin: 0 auto;
    height: 300px;
    width: 340px;
    background: #ddd;
    text-align: center;
}

#right {
    position: absolute;
    top: 0; right: 0;
    width: calc(50% - 170px);
    background: red;
}

@media screen and (max-width: 340px) {
    #middle {
        width: auto;
        max-width: 340px;
    }
    #right {
        display: none;
    }
}


编辑前

max-width 不适用于 position 设置为 absolute 的元素。

你到底想用absolute完成什么,最后你想得到什么样的布局?

删除右侧的最大宽度 div。您还必须将百分比设置为小于 100% 但总计为 100% 才能对响应 divs:

有意义

#container {
  width: 100%;
  text-align: center;
  position: relative;
}
#middle {
  background: #ddd;
  margin: 0 auto;
  position: relative;
  width: 80%;
  max-width: 300px;
  height: 300px;
  display: inline-block;
  vertical-align: top;
}
#right {
  background: yellow;
  width: 20%;
  display: inline-block;
  vertical-align: top;
  position: absolute;
}
@media screen and (max-width: 350px) {
  #right {
    display: none;
  }
  #middle {
    width: 100%;
  }
}
<div id="container">

  <div id="middle">Centered</div>

  <div id="right">Make me responsive</div>

</div>

想法是使用flexbox。并为左列添加一个伪元素,以便使用您现有的标记使中间的元素位于中心。

JSFiddle Demo

#container {
    display: flex;
}
#container:before, #middle, #right {
    border: 1px solid red;
    flex: 1 1 0;
}
#container:before {
    content:"";
}
#middle {
    max-width: 100px;
}
<div id="container">
    <div id="middle">Centered</div>
    <div id="right">Responsive</div>
</div>