1

I am trying to create a 16x16 grid using jquery. I have a main div, and then I'm trying to create the grid within it. I am using for loops, but when the code below runs, I get a 16x32 grid.

Could anyone explain what is going on and why that is happening?

<html>
<head>
    <title>etch-a-sketch</title>
    <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
</head>
<body>
    <div id=main>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type='text/javascript' src='app.js'></script>
</body>

#main {
   height: 192px;
   width: 192px;
   background-color: antiquewhite;
}

.squares {
   height: 10px;
   width: 10px;
   margin: 1px;
   background-color: aquamarine;
   display: inline-block;
}

$(document).ready(function() {
   for(var x = 0; x < 16; x++) {
       for(var y=0; y<16; y++) {
           $("<div class='squares'></div>").appendTo('#main');
       }
   }
});
3
  • 1
    it comes out 16x16 for me. Can you provide a JsFiddle ? Commented Feb 7, 2017 at 17:39
  • I ran it through JSFiddle as well and got the same 16x16 grid. If you have additional code, that may be effecting your grid. Commented Feb 7, 2017 at 17:42
  • add float: left; to squares Commented Feb 7, 2017 at 17:48

2 Answers 2

2

You get a 16x16 grid. When you're using "inline", spaces take place. Just change the CSS code to this:

#main {
  height: 192px;
  width: 192px;
  background-color: antiquewhite;
}

.squares {
  height: 10px;
  width: 10px;
  margin: 1px;
  background-color: aquamarine;
  display: block;
  float: left;
}

Note:

display: block;
float: left;

Sign up to request clarification or add additional context in comments.

Comments

0

I think your thought process was off.. I think the best way to make a 16x16 grid (256 boxes total) would be the way I went below and use css to style them.

The HTML

<div id="main">

</div>

The CSS

#main {
  width: 100%;
}
.squares {
  width:6%;
  height: 50px;
  border: 1px solid red;
  display:inline-block;
}

The Javascript

for(var x = 0; x < 256; x++) {
    $("<div class='squares'>hi</div>").appendTo('#main');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.