如何使div居中并使它们与媒体查询堆叠在一起

时间:2018-10-08 22:39:59

标签: javascript html css

因此,我认为这应该在媒体查询命中之前并排在中间,然后当它命中时应相互叠放。 我不知道为什么它表现得如此。

当ti处于其全宽度时,我尝试使其居中,但它不希望居中;当我使浏览器小于400px时,它们奇怪地堆叠,它们确实堆叠在顶部但没有居中。

.wrapper { 
    margin-top: 15%;
    border : 2px solid #000; 
    overflow:hidden;
  }
  
  .wrapper div {
     min-height: 300px;
     padding: 10px;
  }
  #one {
    background-color: orange;
    float:left; 
    display: inline;
    margin-left: 30%;
    height: 400px;
    width:250px;
    border-right:2px solid #000;
  }
  #two { 
    background-color: orange;
    float:left; 
    margin-right:30px;
    height: 400px;
    width:250px;
    border-right:2px solid #000;
  }
  
  @media screen and (max-width: 400px) {
     #one { 
      float: none;
      margin-right:0;
      bottom: 10%;
      border:0; 
    }

    #two { 
        float: none;
        margin-right:0;
        bottom: 10%;
        border:0;  
      }
  }
<div class="wrapper">
        <div id="one">one</div>
        <div id="two">two</div>
    </div>

1 个答案:

答案 0 :(得分:3)

使用flexbox,您可以轻松进行此操作,而无需媒体查询:

.wrapper {
  margin-top: 15%;
  border: 2px solid #000;
  display: flex;
  justify-content: center; /*center the element*/
  flex-wrap: wrap; /*make them above each other when they cannot fit in one row*/
}

.wrapper div {
  min-height: 300px;
  padding: 10px;
  background-color: orange;
  height: 400px;
  width: 250px;
  border: 2px solid #000;
}
<div class="wrapper">
  <div id="one">one</div>
  <div id="two">two</div>
</div>

您也可以使用inline-block代替float

.wrapper {
  margin-top: 15%;
  border: 2px solid #000;
  overflow: hidden;
  text-align:center;
}

.wrapper div {
  min-height: 300px;
  padding: 10px;
}

#one {
  background-color: orange;
  display: inline-block;
  height: 400px;
  width: 250px;
  border-right: 2px solid #000;
}

#two {
  background-color: orange;
  display: inline-block;
  height: 400px;
  width: 250px;
  border-right: 2px solid #000;
}
<div class="wrapper">
  <div id="one">one</div><div id="two">two</div>
</div>

相关问题