Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons:

https://i.stack.imgur.com/tKZrf.png

I'm looking to add some spacing between these buttons without impacting their alignment with the left and right edges.

This is how I've set up the JSX:

    <View style={globalStyles.stretchContent}>
      <TouchableOpacity
        style={[
          globalStyles.touchableBtnDropOffItem,
          { backgroundColor: Colors.dropOffTabColor },
        ]}
      >
        <Text style={{ color: '#fff' }}>Search</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={[
          globalStyles.touchableBtnDropOffItem,
          { backgroundColor: Colors.dropOffTabColor },
        ]}
      >
        <Text style={{ color: '#fff' }}>Add</Text>
      </TouchableOpacity>
    </View>

And here's the corresponding stylesheet:

  touchableBtnDropOffItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'space-between',
    height: 36,
    marginTop: 20,
    borderRadius: 2,
    marginHorizontal: 5,
  },
  stretchContent: {
    flex: 1,
    color: white,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },

Working with React Native's flexbox layout has presented challenges in achieving this. Applying margin affects the button widths unevenly, causing them to no longer align as intended. For instance, I want the search button to perfectly align with the text All Passengers List (9). However, using marginHorizontal disrupts this alignment by adding margins on both sides of the buttons.

How can I resolve this issue?

Answer №1

  touchableBtnDropOffItem: {
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'space-between',
    height: 36,
    marginTop: 20,
    borderRadius: 2,
    flexBasis: 45%,
  },
  stretchContent: {
    flex: 1,
    color: white,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },

insert flexBasis: 45% into the button and include justifyContent: 'space-between' in the stretchContent. The value of flexBasis can be likened to width when utilizing it within a flexbox

Answer №2

To easily resolve this issue, ensure that both the button and its width are defined. To create space around the button, utilize justifyContent: 'space-around'. If you prefer to have space between the button's left and right sides, you can use justifyContent: 'space-between'.

In your specific scenario:

touchableBtnDropOffItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'space-between',
    height: 36,
    marginTop: 20,
    borderRadius: 2,
    marginHorizontal: 5,
    width: '40%'
  },
  stretchContent: {
    flex: 1,
    color: white,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },

Answer №3

To make the buttons appear side by side with a width slightly less than half (40% or 45%), you can apply the following CSS styling and structure:

(If there are any issues with the syntax provided below in React code, please advise on how to correct it).

<View style={globalStyles.stretchContent}>
   <TouchableOpacity
     style={[
       globalStyles.touchableBtnDropOffItem,
       { backgroundColor: Colors.dropOffTabColor, float: left; },
     ]}
   >
     <Text style={{ color: '#fff' }}>Search</Text>
   </TouchableOpacity>

   <TouchableOpacity
     style={[
       globalStyles.touchableBtnDropOffItem,
       { backgroundColor: Colors.dropOffTabColor, float: right; },
     ]}
   >
     <Text style={{ color: '#fff' }}>Add</Text>
   </TouchableOpacity>
</View>

For the stylesheet:

  touchableBtnDropOffItem: {
     width: 45%;
     flex: 1;
     alignItems: 'center';
     justifyContent: 'center';
     alignContent: 'space-between';
     height: 36px;
     marginTop: 20px;
     borderRadius: 2px;
     marginHorizontal: 5px;
   },

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

Utilizing MakeStyles from Material UI to add styling to a nested element

I was pondering the possibility of applying a style specifically to a child element using MakesStyles. For instance, in a typical HTML/CSS project: <div className="parent"> <h1>Title!</h1> </div> .parent h1 { color: # ...

Incorrect media type linked to Gmail API attachment error

I need help sending a message via the Gmail API in JavaScript, including a JPEG file attachment. My code so far looks like this: $.ajax({ type: "POST", url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart", he ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

Node-sass installation through NPM causing errors

I'm encountering difficulties installing node-sass in a project that builds and runs perfectly on my computer, but is causing major issues on my Surface when trying to install the packages. Note: I've attempted reinstalling and rebuilding the pr ...

Filtering a table with a customized set of strings and their specific order using pure JavaScript

Recently, I've been diving into APIs and managed to create a table using pure vanilla javascript along with a long list of sorting commands that can filter the table based on strings. My goal is to establish an object containing strings in a specific ...

Drawer component from Material-UI placed on top of the sidebar

Currently, I am working on a project where I am using React TypeScript along with Material-UI. The issue that I am encountering is related to the width of the Drawer component provided by Material-UI. By default, the Drawer takes up the entire screen wid ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

Fetching Data Using Cross-Domain Ajax Request

Seeking assistance with a cross-domain Get request via Ajax. The code for my ajax request is as follows: var currency_path = "http://forex.cbm.gov.mm/api/latest"; $.ajax({ url: currency_path, crossDomain:true, type:"GET", dataTyp ...

Send data containing special characters through a GET request in PHP

I am looking for a way to send any text as a GET parameter to a PHP script. Currently, I am simply appending the text like this: action.php?text=Hello+my+name+is+bob This URL is generated using JavaScript and then used in an AJAX request. In action.php, ...

Excessive content and the upper limit of height

I'm in the process of creating a scrolling table with a maximum height, and here's what I've done so far: <table> <tbody style="height: 300px; overflow:auto;"> //php for loop to populate table with <tr>s/<td>s </t ...

Adding Exciting Background Images and Text with CSS

I am looking to enhance my website by incorporating text in the foreground and background images on my webpages for SEO purposes. Can anyone recommend the most effective HTML/CSS approach to achieve this? Currently, I am facing compatibility issues with I ...

Using the "this" keyword within a debounce function will result in an undefined value

It seems that the this object becomes undefined when using a debounce function. Despite trying to bind it, the issue persists and it's difficult to comprehend what is going wrong here... For instance, in this context this works fine and returns: Vu ...

JavaScript Error - Value Not Assigned

I'm having trouble formatting a graph in my code. I keep encountering an undefined error when using console.log to output the data. Here's the snippet of my code: $(document).ready(function () { var graphData = new Array(); $.getJSON("ds ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...

What is the best way to adjust the fontSize of text within a table using Material UI?

In my Material UI table, I am attempting to adjust the fontSize of the contents. However, when I try to modify it using the style={{}} component, the changes are not being applied. <Grid><Typography variant="body1">Fiscal Year </Typography&g ...

Prevent Cross-Site Scripting attacks in Laravel by sanitizing user input, even when allowing HTML tags

What measures can be taken to protect against XSS attacks when a user is allowed to use HTML tags, such as in a textarea element? Avoiding the stripping or escaping of all tags complicates the situation and rules out the option of using {{ }}. It's a ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

What is the best way to upload a file to a server while working with Vue.js in the Filemanager plugin, or how can I access a global function

How can I upload a file to the server using Vue.js in the Filemanager plugin? I have tried multiple methods and the console log shows that the upload was successful, but I am not able to see any files on the server. Does anyone know what could be wrong? & ...