当父元素和子元素具有不同的%宽度时,如何居中子div

时间:2017-08-07 05:59:34

标签: html css responsive-design width centering

我有两行,每行有三个div。当行的宽度为100%且每个div的宽度为28%时,如何将每行中的三个div居中?我也试图让div保持中心并对不同设备(如手机,平板电脑,台式机和笔记本电脑)做出响应。

我试过了:

margin: 0 auto;
display: inline-block;

left: 50%;
right: 50%;



* {
  box-sizing: border-box;
}

body {
  margin: 0;
}


/*Phones*/

[class*="col-"] {
  width: 100%;
  height: auto;
  float: left;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

.insideRows {
  margin: 0 auto;
}

.buttons {
  font-size: 20px;
  color: black;
  border: solid 3px #3366ff;
  padding: 1em;
  margin: 1em;
  text-align: center;
}


/*For Tablets*/

@media only screen and (min-width: 600px) {
  .col-m-5 {
    width: 41.66%;
  }
}


/*For Desktops/Laptops*/

@media only screen and (min-width: 768px) {
  .col-3 {
    width: 28%;
  }
  .col-12 {
    width: 100%;
  }
}

<div class="col-12 row">
  <div class="insideRows">
    <div class="col-3 col-m-5 buttons">Row 1 Column 1</div>
    <div class="col-3 col-m-5 buttons">Row 1 Column 2</div>
    <div class="col-3 col-m-5 buttons">Row 1 Column 3</div>
  </div>
  <div class="insideRows">
    <div class="col-3 col-m-5 buttons">Row 2 Column 1</div>
    <div class="col-3 col-m-5 buttons">Row 2 Column 2</div>
    <div class="col-3 col-m-5 buttons">Row 2 Column 3</div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以将弹性箱用于.insideRows

&#13;
&#13;
* {
  box-sizing: border-box;
}

body {
  margin: 0;
}

.insideRows {
  display: flex;
  justify-content: center;
}


/*Phones*/

[class*="col-"] {
  width: 100%;
  height: auto;
  float: left;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

.insideRows {
  margin: 0 auto;
}

.buttons {
  font-size: 20px;
  color: black;
  border: solid 3px #3366ff;
  padding: 1em;
  margin: 1em;
  text-align: center;
}


/*For Tablets*/

@media only screen and (min-width: 600px) {
  .col-m-5 {
    width: 41.66%;
  }
}


/*For Desktops/Laptops*/

@media only screen and (min-width: 768px) {
  .col-3 {
    width: 28%;
  }
  .col-12 {
    width: 100%;
  }
}
&#13;
<div class="col-12 row">
  <div class="insideRows">
    <div class="col-3 col-m-5 buttons">Row 1 Column 1</div>
    <div class="col-3 col-m-5 buttons">Row 1 Column 2</div>
    <div class="col-3 col-m-5 buttons">Row 1 Column 3</div>
  </div>
  <div class="insideRows">
    <div class="col-3 col-m-5 buttons">Row 2 Column 1</div>
    <div class="col-3 col-m-5 buttons">Row 2 Column 2</div>
    <div class="col-3 col-m-5 buttons">Row 2 Column 3</div>
  </div>
</div>
&#13;
&#13;
&#13;