Nitish Nitish - 4 months ago 15
HTML Question

CSS rearranging divs in a square like manner

I have a div as follows in my angular2 application:

<div align="center">
<div class="box {{box.color}}" ng-repeat="box in boxes" ng-class="{'lit': box.isLit}" ng-click="boxClick(box.id)"></div>
<button class="button button-dark" ng-click="start()">Start</button>
</div>


This looks like following on my screen:

enter image description here

Corresponding CSS:

.box {
height: 50px;
width: 50px;
border: 1px solid black;
margin: 10px;
}

.green {
background-color: green;
opacity: 0.3;
}

.blue {
background-color: blue;
opacity: 0.3;
}

.red {
background-color: red;
opacity: 0.3;
}

.yellow {
background-color: yellow;
opacity: 0.3;
}


I am not so good at CSS. I want to arrange these boxes in a square like manner, i.e. two boxes next to each other and other two bellow them like foursquare.

How can I achieve this?

Answer

You need to float: left your boxes and apply proper width to your boxes wrapper (if you need 2 boxes per line, than wrapper width is 2 * (box width) + padding + margin)

.wrapper {
  width: 200px;
}
.box {
  height: 50px;
  width: 50px;
  border: 1px solid black;
  margin: 10px;
  float: left;
}
.green {
  background-color: green;
  opacity: 0.3;
}
.blue {
  background-color: blue;
  opacity: 0.3;
}
.red {
  background-color: red;
  opacity: 0.3;
}
.yellow {
  background-color: yellow;
  opacity: 0.3;
}
<div class="wrapper">
  <div class="box green"></div>
  <div class="box blue"></div>
  <div class="box red"></div>
  <div class="box yellow"></div>
</div>

Comments