Home > OS >  Page size increases horizontally as I add a margin-top and margin-left to a div
Page size increases horizontally as I add a margin-top and margin-left to a div

Time:09-21

I have created a 3 x 3 column div, using bootstrap, so when I add a margin-left and margin-top to the div, the page size increases horizontally. I want the page size to remain constant while I move the divs.

.col-4 {
  background-color: black;
  width: 100px;
  height: 100px;
  margin: 10px 0 0 10px;
}

.container {
  margin: 100px 0 0 300px;
}
<body>
    <div class="container">
        <div class="row">
            <div class="col-4" id="square_1"></div>
            <div class="col-4" id="square_2"></div>
            <div class="col-4" id="square_3"></div>
        </div>
        <div class="row">
            <div class="col-4" id="square_4"></div>
            <div class="col-4" id="square_5"></div>
            <div class="col-4" id="square_6"></div>
        </div>
        <div class="row">
            <div class="col-4" id="square_7"></div>
            <div class="col-4" id="square_8"></div>
            <div class="col-4" id="square_9"></div>
        </div>
    </div>
</body>

CodePudding user response:

So far whatever I have tried with your code the horizontal size is not changing. However, if you can explain a little about what you are trying to achieve where the problem is coming, I might be able to help.

CodePudding user response:

It's more proper way to deal with boxes with flex system rather than rows and columns which will provide you more flexibility to deal with boxes and avoid default margins and paddings, and will save your container width in easy way.

To achieve this update your HTML code with following

<div class="container">
  <div class="d-flex">
      <div class="col-4" id="square_1"></div>
      <div class="col-4" id="square_2"></div>
      <div class="col-4" id="square_3"></div>
  </div>
  <div class="d-flex">
      <div class="col-4" id="square_4"></div>
      <div class="col-4" id="square_5"></div>
      <div class="col-4" id="square_6"></div>
  </div>
  <div class="d-flex">
      <div class="col-4" id="square_7"></div>
      <div class="col-4" id="square_8"></div>
      <div class="col-4" id="square_9"></div>
  </div>
</div>

And CSS with the following code

.col-4 {
  background-color: black;
  height: 100px;
  margin: 10px 0 0;
  flex: 0 0 32%;
}

.container {
  margin: 100px 0 0 300px;
}

.container > *{
  justify-content: space-between;
}

Enjoy!

  • Related