Guide to adjusting margin size according to specific screen size thresholds?

I've set up a series of reactstrap cards that are dynamically organized into rows. On "md" screen sizes and larger (bootstrap), there will be 3 cards per row, while fewer screens will display 2 cards.

Here's the component:

<Card
    outline
    as='a'
    style={{ cursor: 'pointer', margin: '1rem' }}
  >
    <CardImg top width='100%' src={img}' />
    <CardBody>
      <CardTitle tag='h5'>{this.props.title}</CardTitle>
    </CardBody>
  </Card>

The issue I'm facing is that I only want the middle card to have margins on both sides (marginLeft: '1rem', marginRight: '1rem').

Since the number of cards displayed in each row changes based on screen size, I can't simply apply a style based on multiples of x. Unless I have screen size information, is there a way to create a prop in my parent component that I could pass down to the card component to determine the correct margin setting?

Thank you!

(Any alternative suggestions are appreciated)

More code:

render () {
    return (
        ...
        <div className='row' style={{margin:'0rem'}}>
            {
                disp.map((d, index) => {
                    return (
                        <div className='col-md-4 col-6 d-flex'>
                            <the card component here>
                        </div
                    )
                    ...
                }
            }
        </div>
    ....
                

Answer №1

If you desire spacing between the children, one option is to utilize the gap property along with the flexbox layout. However, it's worth noting that the gap property may not be fully supported in all browsers.

html, body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.card-container {
  background-color: aquamarine;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.card {
  border: 1px solid grey;
  padding: 1rem;
  height: 100px;
}

@media only screen and (min-width: 600px) {
  .card-container {
    flex-direction: row;
  }
  .card {
    flex: 1;
  }
}
<div class="card-container">
  <div class="card">card1</div>
  <div class="card">card1</div>
  <div class="card">card1</div>
</div>

To achieve this, you can use the following selector:

[parent-selector] > * + * 

This selector targets all sibling elements that are direct children of the specified parent-selector (which can be a class or HTML element).

For a top-to-bottom or row-oriented layout, you can utilize:

.card-container > * + * {
    margin-top: 1rem;
}

And if you want space between elements arranged from left to right or in columns, you can use:

.card-container > * + * {
    margin-left: 1rem;
}

html, body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.card-container {
  background-color: aquamarine;
  display: flex;
  flex-direction: column;
}

.card {
  border: 1px solid grey;
  padding: 1rem;
  height: 100px;
}

.card-container>*+* {
  margin-top: 1rem;
}

@media only screen and (min-width: 600px) {
  .card-container {
    flex-direction: row;
  }
  .card {
    flex: 1;
  }
  .card-container>*+* {
    margin-top: 0;
    margin-left: 1rem;
  }
}
<div class="card-container">
  <div class="card">card1</div>
  <div class="card">card1</div>
  <div class="card">card1</div>
</div>

Answer №2

"How can I adjust margin size depending on different screen sizes?"

The Bootstrap responsive spacing classes are designed for exactly that purpose. However, if you're utilizing the grid system (Row > Col), it's recommended to use padding instead of margins to control the space between columns.

If you are using column classes like col-6 col-md-4 to achieve a layout where "there are 3 cards per row for 'md' screen sizes and above, and 2 cards per row for smaller screens.",...

You have the option to dynamically adjust padding on the columns or margins on the cards. For instance, you could apply 3 margin units on medium screens and above (mx-md-3), and 1 margin unit on smaller screens (mx-1):

   <Col className="col-6 col-md-4 py-3">
        <Card className="mx-1 mx-md-3">
           ...
        </Card>
   </Col>

Check out this example in React on Codeply

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

Steps for incorporating a type declaration for an array of objects in a React application with TypeScript

How can I specify the type for an array of objects in React using TypeScript? Here is the code snippet: const SomeComponent = (item: string, children: any) => { //some logic } In this code, you can see that I am currently using 'any' as ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...

Using the preselection feature in the MUI DataGrid can cause the grid to become disabled

I am customizing a mui datagrid to have preselected rows using the following code snippet: const movieCrewList = movieCrew.map((item) => item.id); const [selecteTabledData, setSelectedTableData] = React.useState([]); <DataGrid rows={crewData} c ...

The console is showing an error message stating that the variable "i" is not

Currently, I am developing the dashboard for my discord.js bot. While working on it, I encountered an issue where a variable I created to select an array from my JSON file is being reported as undefined by the console. $(function() { $.getJSON( "./data/ ...

Ways to dynamically update the content of a variable when the input value is modified

Essentially, I have a straightforward code snippet provided below. It is necessary to update the amount and email whenever those are modified by someone. UPDATE: Credit goes to @ellipsis. Your version is close to perfect, except for the data transmission ...

Creating a personalized script in ReactJS: A step-by-step guide

If I have already built a component with Google Chart in ReactJS, and I want to implement a feature that allows the Legend to show/hide data using a JavaScript script provided here, how and where should I integrate this code to work with my chart? Here is ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Embed a local page into an HTML file using PhoneGap

I attempted to load a page within my phonegap application using Jquery .load(), but it isn't functioning because it's on a local machine rather than a server. When I eventually upload the app to PhoneGap Build, my page will still be located in th ...

Adjust the transparency level of the image's mapped area

I need help with changing the opacity of a specific area on an image map when clicked. The image has three areas, but I only want to target and change the opacity of the test2 area regardless of which area is clicked. Since my knowledge of jQuery syntax is ...

The text field is being styled with inline styles automatically

I am trying to set a custom width for a textarea in my form, but the inline styles are automatically overriding my CSS. I have checked my scripts, but I am unsure which one is manipulating the DOM. If you have any insight, please let me know. This is the ...

Issue with npm during installation of REACT - not functioning as expected

After executing all the necessary commands on the command line, including globally installing npm with npm install -g create-react-app, as well as running npx create-react-app <myprojectname> and clearing the npm cache, I consistently encountered an ...

- What are the steps to integrate a different JavaScript plugin into a React project?

Lately, I've come across an issue while trying to incorporate a 3rd party plugin into my practice project in Next.js. Considering that I'm fairly new to React, understanding the 'react way' of doing things has proven to be quite challen ...

Removing the new line using v-if in Vue.js

I want to insert a v-if in the middle of a sentence without creating a new line. This is what I desire: A / B / C / D However, my current output is: A / B / C / D This is the code I am using: <div> {{ A }} / {{ B }} <p v-if="functi ...

The function stripe is not defined in this window

I encountered an issue while working on my stripe checkout project. The loadStripe promise was not functioning properly, forcing me to adjust the code for window.stripe as well. However, this modification did not resolve the problem. Below is my react cod ...

Error: React cannot read property 'any' since it is undefined

I am brand new to React and currently in the process of building a small app by following a tutorial on Udemy. The app includes a form, and while trying to import the redux-form library into my project, I encountered the following console error: https://i ...

What is the best way to add color to a div at the bottom of a page using

https://i.sstatic.net/5kOt7.png I noticed in the image that there is a navy blue color applied to a div at an angle. How can I achieve this effect using Bootstrap in my ASP.NET Core project? ...

Text and Image Coordination

I'm encountering some challenges with a specific section. My goal is for it to resemble this. However, I am currently achieving something different, like this. .timeline { text-align: center; } #about-us { ul { &:before { ...

Error code 2 in Phonegap 2.2.0 iOS file transfer issue

saricsarda2[326:15b03] Executing multiple tasks -> Device: YES, App: YES saricsarda2[326:15b03] -[CDVFileTransfer download:] [Line 313] File Transfer is currently downloading... saricsarda2[326:15b03] File Transfer has been completed with response code ...

Tips for updating label color when an error occurs in a React application

Can you please explain how to change the color of labels and input fields in error state using Material? Here is what I have tried: <FormControl> <TextField required error ...