如果页面大小有一定的限制,我如何将三个div对齐并让其中一个消失



所以我有三个div和class,如代码片段所示。

/* CSS Question #4 */
        .box1 {
            background-color: green;
            width: 200px;
        }
        .box2 {
            background-color: grey;
            width: 200px;
        }
        .box3 {
            background-color: aqua;
            width: 200px;
        }
<div>
              <h1>Arrage the div:</h1>
              <div>
                  <div class="box1">This one should be on the left side of the page</div>
                  <div class="box2">This one should be on the right side of the page</div>
                  <div class="box3">This one should be at the center of the page and it should disappear if the page become less than 800px.</div>
              </div>
          </div>

我试图使box1位于左侧,使box2位于右侧,对于box3,如果页面小于800px,则它需要位于中间并消失,如div本身所述。

我已经将float:left分配给box1,将float:right分配给box2,使它们分别向左和向右对齐。但我不确定如何让box3位于中间,并在页面小于800px时消失。

我认为,您应该使用媒体查询。下面是一些媒体查询的参考链接。

http://www.w3schools.com/cssref/css3_pr_mediaquery.asp
http://learnlayout.com/media-queries.html

上述解决方案,

    .box1 {
            background-color: green;
            width: 50%;
            float:left;
          }
    .box2 {
             background-color: grey;
             width: 50%;
             float:right;
          }
    .box3 {
             background-color: aqua;
             width: 100%;
             clear:both;
          } 

媒体查询

@media screen and (max-width: 800px) {
    .box3 {
           display:none;
    }
}

Cs完全取决于你想要的各种框的大小,我个人会为所有三个div设置百分比,比如宽度为"33.33333333%",然后写一个针对@media的媒体查询(最大宽度:800px),然后将中间的div设置为不显示,左右两侧的宽度为50%。这应该会给你带来想要的效果。

您还应该将第三个div移动到第二个位置,或者使用flex对它们进行不同的排序:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

          <div class="boxes">
              <div class="box1">This box should be on the left side of the page</div>
              <div class="spacer"></div>
              <div class="box3">This box should be at the center of the page and should disappear if the page is less than 800px.</div>
              <div class="spacer"></div>
              <div class="box2">This box should be on the right side of the page</div>
              <br/>
          </div>

    .boxes {display: flex;}
    .box1 {
        background-color: green;
        width: 200px;
        float: left;
    }
    .box2 {
        background-color: grey;
        width: 200px;
        float: right;
    }
    .box3 {
        background-color: aqua;
        width: 200px;
        flex: auto;
    }
    .spacer {flex-grow: 1}
    @media screen and (max-width: 800px) {
        .box3 {
               display:none;
        }
    }

我就是这么做的。。。

最新更新