user7607612
user7607612

Reputation:

How to center multiple inner divs horizontally?

I've tried various post answers but still not able to center the divs I had.

Here is my 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>

The CSS I was using is below:

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;
}

I used float:left for placing divs next to each other but I had issues with height. I'm using display:inline-block for that instead. Jsfiddle link : https://jsfiddle.net/Lywbygum/

Upvotes: 1

Views: 51

Answers (4)

Michael Coker
Michael Coker

Reputation: 53709

You can use display: flex; justify-content: center; on the parent.

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>

Upvotes: 1

Johannes
Johannes

Reputation: 67798

With the CSS you aready have you can add text-align: center to .maindiv to center its child elements (because they are inline-blocks).

Upvotes: 0

Jorden
Jorden

Reputation: 163

Set text-align:center .maindiv.

Upvotes: 0

mayersdesign
mayersdesign

Reputation: 5310

Just add text-align: center; to the main 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>

Upvotes: 2

Related Questions