What causes the gap between a parent div and inner div in react components?

I have a relatively simple React component that I'm working on. Even though I am quite new to React, I have tried various methods to eliminate the white space issue but so far have been unsuccessful in determining what is causing it. Negative margin seems to be a temporary fix, but I understand that it's not the best solution. Can someone please provide guidance on how to resolve this?
import React, { Component } from 'react';

class Shopdetail extends Component{
    constructor(props){
        super(props);
        this.state={            
            data: this.props.data,
            redirect:false

        };        
    }
    componentDidMount(){
        console.log(this.props.match.params.idUser);
    }
        render(){
            return(
                <div style={{ verticalAlign: 'top',margin:'0',clear:'both'}}>
                    <div style={{background:'#cc5',width:'100%',height:'100px',verticalAlign: 'top',boxSizing: 'border-box',clear:'both',padding:'0'}}>Hey</div>
                </div>

            )
        }
}
export default Shopdetail

Here is a screenshot for reference: https://i.sstatic.net/eZFTa.png

Answer №1

To eliminate margin from the body, you can either remove it entirely or include the following code:

body{
   margin : 0px !important;
}

Answer №2

Each web browser comes with its own default styles for every HTML element.

Consider how the font size of an h1 tag is typically larger than that of a p tag...!! These default styles are part of what's known as the User Agent StyleSheet.

The User Agent StyleSheet includes predefined margin and padding values for each HTML tag (with different values for each tag).

A recommended practice is to always reset these default margin and padding values using universal selection at the start of a project:

*,
*:after,
*:before {
  margin:0;
  padding:0;
  box-sizing:border-box;
}

Answer №3

For a clean slate in your CSS, consider using this reset code at the beginning of your stylesheet:

<style>
/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
</style>

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

Clicking on tabs causes their content to mysteriously vanish

I am working on creating a dynamic menu using jQuery that switches content based on tabs. However, I am facing an issue where clicking on a different <li> item causes the content to disappear. Each list item should correspond to different content sec ...

Encountering issues with saving information to MongoDB

I recently started working with the MERN stack and I am trying to save user information in MongoDB, which includes two string attributes: "name" and "role". However, I encountered an error in the browser console stating "Failed to load resource: Request t ...

"Using a triangular background shape in JavaScript instead of a traditional circular

I want to add a unique effect to my site inspired by the AnimatedHeaderBackgrounds demo available at this link. My twist on this effect involves using upward-moving triangles instead of circles. I've explored various resources, including Stack Overfl ...

Click on the div to automatically insert its text into the textarea

I am looking for a way to enable users to edit their posts easily. My idea is to have them click on a link, which will then hide the original div containing their post and reveal a new div with the old text inside a textarea for editing. Despite searching ...

Incorporating the <sub> element while maintaining the line height

I am facing a challenge with formatting text that includes subscripts and superscripts tags. For example: <div>hello <sub>world</sub>, how are you? Translated as logical aggregates or associative compounds, these characters have been int ...

Fascinating CSS quandary: does the transparency of a parent element impact the transparency of a child element that is absolutely positioned, but not in relation

Check out this test case: https://jsbin.com/merujogudo/1/edit?html,css,output Should the element with .test class be transparent or not? Note: The current state is as follows: In Chrome and Firefox (latest versions): transparent In IE11: opaque It wou ...

React: Blur input element when escape key is pressed

I need help with a functionality for an input tag. When the escape key is pressed, I want the focus to be removed from the input element so that there is no text cursor or any styling related to focus (meaning user input will not be registered in the input ...

How does the `useTracker` function determine which data subscriptions to establish?

As I delve into the Meteor basic tutorial, I am facing challenges with the automatic update of the "task list" when inserting an item. Hence, I decided to troubleshoot. The primary app component utilizes the useTracker function hook to "subscribe" to chan ...

The contents of the div do not display when the button is pressed except in jsfiddle

I have written a script that triggers the appearance of a div where users can adjust the time settings for a timer. The functionality works perfectly on JSFiddle, with the div displaying as intended. However, when tested on other online IDEs such as Coding ...

Specify the BUILD Port for your React JS project

After executing npm run build, I proceed to run npm serve -s on the build directory. The resulting output displays: Local: http://localhost:5000 I would prefer the application to be hosted at localhost:3000 instead. How can I specify this spec ...

What is the CSS technique for concealing the content of an ordered list item while retaining the marker?

In our order process, we utilize an ordered list to display the steps in sequence: <ol> <li>Products</li> <li class="active">Customer</li> <li>Payment</li> </ol> On desktop view, it appears a ...

What is the best way to implement Infinite scroll alongside Virtual scroll in Ionic 3?

Having recently delved into the world of Ionic and Angular, I am encountering some difficulties with implementing Infinite scroll alongside Virtual scroll. Despite pushing data such as images, text, and click functions from TypeScript, only empty Ionic car ...

Steps for displaying the contents of a file from Firebase storage on a React component

I uploaded a file to Firebase storage, and I want my app to be able to access and display the contents of that file within my class component div. Currently, when I try to access the file, it just opens in a new tab instead. class ScanResult extends Comp ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

Error Message: ApolloError - Server issue: Unable to complete request - Status code 401 received

I'm encountering an issue when trying to start my NextJS project. It works fine on my computer using the command "npm run dev", but I run into problems when deploying it on Vercel or cloning the git repository on another computer at school. I suspect ...

Implementing form validation for dropdown lists with Material-UI React: A comprehensive guide

I'm still learning React and I've been using material-ui for form validation. Everything was going smoothly until I encountered an issue with validating a dropdown list. Whenever I try to validate it, an error occurs: "Cannot read property ' ...

Clicking on the modal button causes the code to run multiple times in JQuery and JavaScript

Hello, I'm experiencing an issue where the code inside a modal is being executed multiple times when the modal button is clicked. For example, if I click the modal button once, the code runs once; if I click it twice, the code runs twice, and so on. ...

Issue with Typescript typing for the onChange event

I defined my state as shown below: const [updatedStep, updateStepObj] = useState( panel === 'add' ? new Step() : { ...selectedStep } ); Additionally, I have elements like: <TextField ...

Unable to update to the most recent version of React-Bootstrap

I'm facing an issue while trying to upgrade to the newest version of react-bootstrap. When I run: npm install --save react-bootstrap The following message appears: npm notice created a lockfile as package-lock.json. You should commit this file. npm ...

Prevent the bootstrap header in a table from scrolling by enclosing it in

I am encountering an issue with fixing the headers of multiple tables in a page within their dedicated divs. Despite trying various methods, I haven't been successful as the fixed header overflows the div. I want to confine it within the div. Additio ...