如何水平居中多个内部div?

时间:2017-04-10 17:34:37

标签: html css

我尝试过各种答案,但仍无法将我所拥有的div放在中心位置。

这是我的Html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Dashboard</title>
    <link rel="stylesheet" href="dashboard.css">
  </head>
  <body>
    <div class="maindiv">
        <div class="row1">

        </div>

        <div class="row1">

        </div>

        <div class="row1">

        </div>
    </div>





  </body>
</html>

我使用的CSS如下:

body{
  font-family: Myriad Set Pro;
  background-color: #f7f8f9;

}

.maindiv{
  padding: 20px;
  width: 70%;
  margin: 0 auto;
  border: 1px solid black;

}

#innerrow1{
  width: 80%;
  position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;

    margin: auto;
}

.row1{
  margin: 0 auto;
  display: inline-block;
  background-color: #efefef;
  border: 1px solid #b5b5b5;
  width : 300px;;
  height: 290px;
}

我使用float:left将div放在一起,但我遇到了高度问题。我改为使用display:inline-block。 Jsfiddle链接:https://jsfiddle.net/Lywbygum/

4 个答案:

答案 0 :(得分:2)

只需将text-align: center;添加到主div:

body {
  font-family: Myriad Set Pro;
  background-color: #f7f8f9;
}

.maindiv {
  padding: 20px;
  width: 70%;
  margin: 0 auto;
  border: 1px solid black;
  text-align: center;
}

#innerrow1 {
  width: 80%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

.row1 {
  margin: 0 auto;
  display: inline-block;
  background-color: #efefef;
  border: 1px solid #b5b5b5;
  width: 100px;
  height: 290px;
}
<div class="maindiv">
  <div class="row1"></div>
  <div class="row1"></div>
  <div class="row1"></div>
</div>

答案 1 :(得分:1)

您可以在父级上使用display: flex; justify-content: center;

body {
  font-family: Myriad Set Pro;
  background-color: #f7f8f9;
}

.maindiv {
  padding: 20px;
  width: 70%;
  margin: 0 auto;
  border: 1px solid black;
  display: flex;
  justify-content: center;
}

#innerrow1 {
  width: 80%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

.row1 {
  background-color: #efefef;
  border: 1px solid #b5b5b5;
  width: 100px;
  height: 290px;
  margin: 0 1em;
}
<div class="maindiv">
  <div class="row1">

  </div>

  <div class="row1">

  </div>

  <div class="row1">

  </div>
</div>

答案 2 :(得分:0)

设置text-align:center .maindiv。

答案 3 :(得分:0)

使用CSS,您可以将private int calcDepth( Tree<K, V> x, K keyIn, int currentLevel){ if(x == null) return -1; // key doesnt exist if this is true if (x.key.compareTo(keyIn) == 0) return currentLevel; //BASE CASE if (x.key.compareTo(keyIn) < 0){ // check left tree return calcDepth(x.left, keyIn, currentLevel+1); } if (x.key.compareTo(keyIn) > 0){ // check right tree return calcDepth(x.right, keyIn, currentLevel + 1); } return -1; } 添加到text-align: center以使其子元素居中(因为它们是内联块)。