When I set the margin to 0 for both the div and body elements, the divs still have margins

Attempting to place a canvas inside a div named touch-container, with 3 additional divs on top and sizing them using javascript.

The issue arises as each of the 3 divs appear to have a margin that fills up the remaining space in the container, despite specifying a margin of 0.

Click here for jsFiddle preview, inspect to see the mysterious margin: Jsfiddle

HTML:

<div id = "touch-container">
    <div id = "touch-left" class = "touch-control"></div>
    <div id = "touch-middle" class = "touch-control"></div>
    <div id = "touch-right" class = "touch-control"></div>
    <canvas id = "canvas" width = "960" height = "560"></canvas>
</div>

CSS:

body {
  margin: 0;
}

#touch-container{
  width: 964px;
  height: 560px;
  display: inline-block;
  margin: 0;
}

.touch-control{
  position: relative;
  margin: 0;
}

#touch-left{
  background-color: red;
}

#touch-middle{
  background-color: green;
}

#touch-right{
  background-color: blue;
}

JS:

var leftTouch = document.getElementById('touch-left');
var upTouch = document.getElementById('touch-middle');
var rightTouch = document.getElementById('touch-right');

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");

var width = (canvas.width > canvas.height ? canvas.width : canvas.height);
var height = (canvas.height > canvas.width ? canvas.width : canvas.height);

leftTouch.style.width = (width/ 4) + 'px';
leftTouch.style.height = height + 'px';

upTouch.style.width = (width/ 2) + 'px';
upTouch.style.height = height + 'px';

rightTouch.style.width = (width/ 4) + 'px';
rightTouch.style.height = height + 'px';

ctx.fillRect(0,0,canvas.width, canvas.height);

The colored squares should make a black square at the bottom, followed by red, green, and blue squares from left to right occupying 25%, 50% 25% of the container, rendering the black canvas invisible.

Answer №1

Your elements (squares) are not properly positioned because you have not added the float property to them. To ensure the squares are in the same line, you should use float:left;. Using display:inline-block; will not achieve the desired result as it only works for text:

Jsfiddle

css:

#touch-container{
    width: 964px;
    height: 560px;
    display: block; /* updated */
    margin: 0;
}

#touch-left{
    background-color: red;
    float: left; /* updated */
    display: block;
}

#touch-middle{
    background-color: green;
    float: left; /* updated */
    display: block;
}

#touch-right{
    background-color: blue;
    float: left; /* updated */
    display: block;
}

Answer №2

When dealing with block and inline-block level elements, the concept of margin comes into play. Block elements like divs stack on top of each other, and by setting margin: 0, you can remove any space between them.

If your goal is to position the divs on top of a canvas element, one way to achieve this is through absolute positioning.

.touch-control {
    position: absolute;
    top: 0;
}

After applying the CSS, you can then use JavaScript to adjust the 'left' property of each div or manually position them with additional CSS styles.

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

A Guide to Displaying HTTP Error Messages on the Angular Login Page

When encountering a form validation failure on my login page, I utilize ngMessage to display an error message. However, I now want this div to be displayed in the event of an HTTP 500 error. While I can retrieve the corresponding error message when an HTTP ...

What is the best way to transmit multiple files to the server in node.js?

As a newbie to the world of web development (I've only been coding with luau for around a year), I'm encountering an issue when trying to send multiple files when my server is pinged. Specifically, I want to include a separate style.css file and ...

Selenium can locate an element by its CSS selector that comes after a specific element

How can I locate the text "Interesting" which is the first occurrence of the class b after h1.important when using Selenium? <div class="a"> <div class="b">Not interesting</div> </div> <div class="title"> <h1 c ...

Is there a way to prevent the onClick function from being triggered during the rendering process?

Why is the function being called every time a React component is rendered, even though it shouldn't be? For example: const onClick = () => { console.log('hi'); } <button onClick={onClick}>CLICK</button> I am curious abo ...

When using ReactDOM.render, make sure to provide a function as the last optional `callback` argument

I recently started learning React and I encountered the following error message after writing this code: ReactDOM.render Expected the last optional `callback` argument to be a function. `Instead received: Object` This is my code var Stats = Reac ...

Automatically fill in a custom entity using JavaScript even when the GUID of the parent entity is unknown within Dynamics 365

Recently delving into client-side scripting, I have been tirelessly searching through Google and various communities for answers without success. Allow me to present my issue for a clearer understanding of the predicament. I have established two custom en ...

What are the steps to fix the eslint error related to "Generic Object Injection Sink"?

I'm attempting to access a JSON array, but every time I try to read the array/value by passing the JSON object key like this- json[key] An Eslint error occurs- [eslint] Generic Object Injection Sink (security/detect-object-injection) I understand ...

Utilizing Bootstrap Modal to Upload an Image

I'm facing an issue with uploading an image using a Bootstrap modal. The problem I encounter is that even after selecting an image, I continue to receive the validation error message "Your upload form is empty". Below is the script for my form in the ...

Synchronization issues with form validation

I'm currently tackling an assignment for my CS50 course and I am relatively new to working with Jquery/Ajax. As part of this task, I am developing a registration form where users must enter a unique username. To achieve this, I have implemented code t ...

Top strategies for avoiding element tampering

What is the best solution for handling element manipulation, such as on Chrome? I have a button that can be hidden or disabled. By using Chrome's elements, it is possible to change it from hidden/disabled to visible/enabled, triggering my click functi ...

angularslideables retro animation

I'm currently using the AngularSlideables library to toggle a modal within my Ionic project. You can check out a functional example in this fiddle: http://jsfiddle.net/3sVz8/19/ However, I am facing an issue where the initial height is set to 100% i ...

Please request user input in order to generate a multiplication chart

Is there a way to ensure that the program works properly so that when the user inputs a value, it is included in the multiplication table? <html> <head> <title> Multiplication Table </title> <style> body{ font-family: aria ...

Storing knockout view model data in a database and fetching it back

I am currently working on a web form that utilizes knockout, and I need to add a new feature that allows users to save the form as a draft in the database. Later on, they should be able to load it again to make modifications or submit it. Is there a built ...

Tips for ensuring proper function of bullets in glidejs

I am currently working on implementing glidejs as a slider for a website, but I am facing issues with the bullet navigation. The example on glidejs' website shows the bullets at the bottom of the slider (you can view it here: ). On my site, the bullet ...

What is the best way to recreate this grid-like design using CSS?

By utilizing clever techniques such as margins and outlines, I was able to design the following. If you'd like to take a look at the live website, it can be found at https://i.sstatic.net/kl0an.jpg The CSS code that I used is as follows: body { ma ...

Tips for showcasing retrieved JSON with jQuery's ajax functionality

Below is the jquery code I am working with: $.ajax({ type: "POST", url: "Ajax/getTableRecord", data:{ i : id, t: 'mylist'}, dataType: 'json', success: function(data){ alert(data); ...

Obtain the data from a different HTML element

When a user clicks on a button, I want to send the value of an input element in Angular2. What would be the most effective approach for achieving this? <input type="text" class="form-control" placeholder="Search for images..." /> <span class="i ...

Django raised a ValueError stating that the view usermanager.views.group_perm did not provide an HttpResponse object, but instead returned None

I'm currently in the process of developing a News Website. However, I've run into an issue when attempting to delete permissions from a group - I keep getting the same error. Oddly enough, the codes above this particular function are nearly ident ...

Is it possible to add a CSS filter to a background image?

How can I achieve a background image with blur effect using CSS? body{ background-color: transparent !important; background-image: url("img.jpg"); background-size: cover; background-position: center center; background-repeat: no-repea ...

Orders in WooCommerce are being mysteriously created with no information provided and stuck in a pending payment state

Are you experiencing the issue of blank orders being generated in WooCommerce with no details and a pending payment status? I am utilizing the WooCommerce plugin along with the Elavon payment gateway, and although everything seems to be set up correctly, t ...