How to horizontally center a responsive div with multiple objects inside

Asked

Viewed 640 times

0

I’d like to put as much as Rectangle possible within the mainDiv, and then centralize the mainDiv horizontally. For example, in this image we can see eight Rectangle within the mainDiv, however has a space on the right side, I would like to centralize the mainDiv, to leave the same margin on the right and left side

inserir a descrição da imagem aqui

<div id="mainDiv" >
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
    <div id="Rectangle" style="width: 200px; height: 300px; background: #4d5f8d; margin-left: 20px; margin-top: 30px; float: left;"></div>
</div>

  • explain this better

  • @Felipeduarte I already asked the question.

1 answer

2


Would that be?

.Rectangle {
  width: 200px; 
  height: 200px;
  background: #4d5f8d; 
  margin-left: 20px; 
  padding: 10px;
  margin-top:10px;
  }
  .mainDiv {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
  }
<div class="mainDiv" >
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
    <div class="Rectangle" ></div>
</div>

when reaching the resize limit the element goes down, thus keeping the elements centered

Browser other questions tagged

You are not signed in. Login or sign up in order to post.