What could be causing my chessboard to not wrap around properly with flexbox?

I have been working on creating an 8x8 chessboard by following this example: https://codepen.io/sammyslamma/pen/gJeOwY

  
    .flex-container {
        display: flex;
        flex-flow: row;
        flex-wrap: wrap;
        height: 336px;
        width: 336px;
    }

    .chessboard {
        border: 1px solid black;
        width: 40px;
        height: 40px;
    }

    .chessboard div:nth-child(odd) {
        background-color: blue;
    }
    <div class="flex-container">
        <div id="tile">
        <script>
        for(x=0; x<64;x++) {
          var tile = document.createElement('div');
          tile.className = "chessboard";
          document.getElementById('tile').appendChild(tile); }
        </script>
        </div>
    </div>

I have created 64 divs under the class name "chessboard", but I am having trouble making the squares go across to form an 8 by 8 grid. I have tried setting the height, width, and flex-basis to 12.5%, but it didn't work as expected.

Any guidance on how to achieve the desired layout would be greatly appreciated. Thank you!

Answer №1

Let's address a couple of important errors in the example you provided:

display: flex only affects the direct children of an element - in this case, the element #tile is considered the child, while your .chessboard elements remain unaffected.

Regarding the coloring, the selector .chessboard div:nth-child(odd) targets odd-child divs within .chessboard, not the chessboard elements themselves.

However, if you intend to create an actual chessboard, the current approach may not be suitable due to two main reasons:

  1. A chessboard is traditionally an 8x8 grid, not a single array of squares. Flexbox may arrange children in a way that creates rows with 7 or 9 squares, which is not ideal.
  2. The pattern of odd numbering is incorrect for a chessboard; you should have odd numbers in even rows and even numbers in odd rows.

While some have suggested using CSS grid, an alternative solution could be utilizing the classic <table> element in HTML. Here's an example implemented using Haml for simpler HTML creation: https://codepen.io/anon/pen/rgdNgq?editors=1111.

The key CSS styles applied are:

.chess-board {
  border: 1px solid gray;
  border-collapse: collapse;
  border-spacing: 0;
}

.chess-board td {
  padding: 0;
  width: 4rem;
  height: 4rem;
}

.chess-board tr:nth-child(odd) td:nth-child(even),
.chess-board tr:nth-child(even) td:nth-child(odd){
  background: #222;
}

Using a table structure ensures a fixed 8x8 grid for the chessboard, which is more suitable for this specific layout. While CSS Grid can also achieve this, it offers more flexibility in grid structures, which is unnecessary in this case.

Additionally, a table structure allows for easier navigation and styling of individual rows and columns compared to ungrouped cells, where you would need to calculate each cell's position manually.

Answer №2

Add the class "flex-item" to the inner div element.

.flex-item {
 justify-content: center;
 align-items: center;
}

Answer №3

Take advantage of grids instead of flexbox with this code snippet.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  grid-gap: 1px;
  max-width: 640px
}

.chessboard {
  border: 1px solid black;
  width: 80px;
  height: 80px;
  margin: 1px 
}
<div id="tile" class="container">
  <script>
   for(x=0; x<64;x++) {
     var tile = document.createElement('div');
     tile.className = "chessboard";
     document.getElementById('tile').appendChild(tile);}
   </script>
 </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Increase value by 1 with the push of a button within two specified ranges using JavaScript

I am looking to create buttons that will increase the value of both the first and second range by 1 when pressed, as well as decrease the value of both ranges by 1 when pressed. Here is my code: function run(){ var one = document.getElementById("rang ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

Creating valuable properties in TypeScript is a skill that requires knowledge and practice

In TypeScript, there is a unique feature available for defining properties with values using the `value` keyword. class Test { constructor(private value: number = 123) { } public MyValueProperty: number = 5; } Here is how you can define such ...

Drop and drag the spotlight

On my website, I am looking to implement a feature that will make it easier for users to identify the drag and drop area. I found a code snippet on JSFIDDLE that works perfectly there. However, when I tried to use it on my local server, it doesn't se ...

Menu Overlay (jQuery/CSS)

I am in the process of developing a website that is optimized for both mobile and desktop devices. I am currently brainstorming ideas for the main navigation, which I envision as an overlay that slides down similar to . However, I am struggling to create ...

Creating a Cascading State and City Dropdown Using Knockout JS and JSON Data

When the user selects a state from two fields, state and city, a call is sent to the server returning JSON data. This data needs to be used to update the city field in knockout, but there seems to be an issue with the syntax of getting the ajax data. Here ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

https://i.sstatic.net/fkIyh.png Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navig ...

Detecting a targeted POST event in JavaScript without any libraries

In a situation I'm facing, an AngularJS website is not loading jQuery (except for jQLite). My goal is to monitor events with particular parameters. Unfortunately, I'm unable to make any changes to the source code. However, by examining the event ...

Calculating and displaying the output on an HTML page: A step-by-step guide

Within my HTML, I have two values stored in Session Storage: "Money" and "Time". These values are based on what the user inputted on a previous page. For example, if someone entered that they need to pay $100 in 2 days. My goal is to generate a list that ...

The Stencil EventEmitter fails to send data to the Vue instance

Attempting to develop a custom component using Stencil with an input feature. The goal is to create a component with an input field that, upon value change, emits the input to the Vue instance and logs this event to the console (later updating the value in ...

Retrieve a value from a PHP database table and transfer it to a different PHP webpage

I have values retrieved from a database and I need to select a row from a table and pass those values to the next PHP page, OInfo.php. I attempted to use Javascript to place those values in textboxes, but upon clicking the continue button, the values are n ...

Obtain the final result once all promises have been successfully resolved in a loop

Here is an array of IDs: let idsArray = [1, 2, 3, 4, 5]; How can I ensure that a promise is returned only after all calls made within the loop are completed? let deferredPromise = $q.defer(), finalResult = []; fo ...

Send a file from a form using Gatsby to getform.io using the axios library

I am facing an issue with my getform.io form where the file is not getting uploaded properly. The file appears as [] and the files tab remains empty. Upon checking the network tab, I noticed that my request payload includes {email: "[email protec ...

Create dynamic Bootstrap 4 menus featuring three levels of navigation - the initial dropdown sub-menu may not display any selectable options

Using Bootstrap 4 and jQuery 2.2.4, I've created a navbar with three layers of menus, comprising two levels of drop-downs from the top-most level. Everything works smoothly except for a glitch on mobile devices. The menu collapses to the hamburger ic ...

Tips for designing a horizontal sub-navigation menu using CSS?

I have limited experience with list menus and am struggling to create a horizontal submenu with its own styling. Despite multiple attempts, I have been unsuccessful in finding a solution and have put the project on hold for now. Here is what I currently h ...

Secondary menu

Is there a way to create a sub navigation menu that only changes once I click a link in the main navigation bar, without refreshing the entire page? Any help would be greatly appreciated. http://jsfiddle.net/qrn8Q/ Thank you. HTML Code: <header ...

What is the best way to include a new class into the current class in this particular scenario?

Just starting out with Javascript and Jquery, so please bear with me if this question seems basic I'm dynamically constructing HTML like this: var favoriteresultag = '<ul>'; favoriteresultag += "<section id='"+name+"' ...

Plupload is not compatible with ng-dialog

I'm currently attempting to integrate plupload into a modal window that is generated by ng-dialog. Here is the code I am using: $scope.showManager = function(){ ngDialog.open({ template: '/template/fmanager.html', controller: &apo ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Animation controlled by a button

I'm working on a project that involves creating a cartoon version of a record player. I want to incorporate an animation where the play button on the side toggles the spinning motion of the record using webkit, while also starting the audio track. The ...