Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically & horinzontally align multiple div children in container

Tags:

html

css

I currently have the following code:

<div id="container">
     <div class="card">1</div>
     <div class="card">2</div>
     <div class="card">3</div>
     <div class="card">4</div>
</div>

<style>
    #container{
       width:100%;
       height:100%;
       overflow-y:auto;
       position:absolute;
       left:0; top:10px;
       padding:10px;
    }

    .card{
       width:100px; height:100px; margin:10px;
       float:left;
    }
</style>

I am trying to vertically and horizontally align the div boxes so that the more boxes that appear, it still stays both vertically and horizontally centred in the container. For example:

enter image description here Example of what it would look like with 4 cards which fit in the container..

enter image description here Example of what it would look like with 12 cards which overflow in the container..

enter image description here Example of what it would look like with cards that dont fit in the container..

like image 263
MichaelH Avatar asked Sep 25 '22 22:09

MichaelH


2 Answers

DEMO

HTML

<div class="container">
  <div class="container-wrapper">
    <div class="card"></div>
    <div class="card"></div>
    <div class="card"></div>
    <div class="card"></div>
    <div class="card"></div>
  </div>
</div>

CSS

.container {
  position: relative;
  display:table;
  background: red;
  width:100%;
  height: 100%; /* auto is default, you can have ur height here */
}

.container-wrapper {
  display: table-cell;
  margin:auto;
  text-align:center;
  font-size:0;
  width:90%;
  height:90%;
  vertical-align:middle;
}

.card {
  display: inline-block;
  height:100px;
  width:100px;
  border: 1px solid #ddd;
  background: #eee;
  margin:10px;
}

DEMO 2 with some height of the container

like image 176
4dgaurav Avatar answered Sep 29 '22 23:09

4dgaurav


Try Flexbox DEMO

#container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0 auto;
  flex-wrap: wrap;
  box-sizing: border-box;
}

.inner {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  max-width: 750px;
  margin: 0 auto;
  flex-wrap: wrap;
}

.card{
  width:100px; 
  height:100px; 
  margin:10px;
  border: 1px solid black;
 }
<div id="container">
  <div class="inner">
     <div class="card">1</div>
     <div class="card">2</div>
     <div class="card">3</div>
     <div class="card">4</div>
     <div class="card">1</div>
     <div class="card">2</div>
     <div class="card">3</div>
     <div class="card">4</div>
     <div class="card">3</div>
     <div class="card">4</div>
  </div>
</div>
like image 42
Nenad Vracar Avatar answered Sep 30 '22 00:09

Nenad Vracar