neo neo - 1 year ago 70
CSS Question

How to align div's to center when size of adjacent div's overflows screen width

My question must be little bit confusing and will have many related questions. But I think my case is different.

Please run the code in full screen and reduce the size of the screen to around such that there will be

  • Two boxes per row

  • One box per row

In both cases there will be lot of empty space to right of the adjacent box, what I want is to align the box to the center and make look both right and left equal when such a case occurs. It should work for both the cases (Two boxes per row & One box per row)

background-color : #E9EAED;
position: relative;
width: 400px;
float: left;
border: 1px solid rgba(35, 173, 278, 1);
height: 120px;
background-color: white;
cursor: pointer;
margin: 15px 15px 15px 15px;


<!DOCTYPE html>
<div class="box">box 1 </div>
<div class="box">box 2 </div>
<div class="box"> box 3</div>
<div class="box"> box 4</div>
<div class="box">box 5 </div>
<div class="box">box 6 </div>
<div class="box"> box 7</div>
<div class="box"> box 8</div>
<div class="box"> box 9</div>
<div class="box"> box 10</div>
<div class="box">box 11 </div>
<div class="box">box 12 </div>
<div class="box"> box 13</div>
<div class="box"> box 14</div>

Answer Source

Add to body

body {
text-align: center;

And change the box class

.box {
float: left; //remove this
display: inline-block; //add this
text-align: left; // that your text would be aligned normally again
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download