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

jQuery slideToggle function not working properly when clicking on a link within a div

I am facing a slight issue with the slideToggle function when there is a link inside the slideup panel. My goal is to create a button that, when clicked, will slide up a div displaying related posts. Subsequently, when another button or project link is cli ...

Creating a link button using JavaScript

I have integrated a Setmore code on my website to facilitate appointment booking, which triggers a popup similar to what you would see on a hotel reservation site. <script id="setmore_script" type="text/javascript" src="https://my.setmore.com/js/iframe ...

Looking to compare values within an ng-repeat loop?

I am trying to compare values within the context of an ng-repeat directive. Specifically, I need to compare the current value with the previous value in the array being iterated over by ng-repeat. For example, if my array contains the values [2,3], how can ...

CSS: Troubles with Element Widths

I'm dealing with a list item that contains an image, like so: <ul> <li> <img></img> </li> </ul> The image is not filling the entire width of the list item. Is there a way to make the list item shr ...

Use the jQuery .GET() method two times to retrieve data and obtain the outcomes

My code involves making a series of GET calls where the returned data from one call is used in another call before returning the final results. However, I want to ensure that my program waits until all the data is retrieved. This is what I have come up wi ...

What is the best way to add uppercase letters exclusively?

Is there a way to dynamically style uppercase text within an <h2> tag that is generated based on an image's alt text? I'm thinking of using javascript / jquery to identify the uppercase text and encase it in a <strong> tag, then appl ...

What is the process for transforming OpenTopography point cloud color data from NSF into RGB values?

I'm currently working on a small project focused on visualizing NSF OpenTopography data in a point cloud using three js. While I've been able to plot the data points successfully, I'm struggling to understand the color values associated with ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

Displaying AJAX Confirmation in a Popup Window

My form is set up to insert data into a database via an AJAX request. Upon successful insertion, the "rentinsert.php" will display a success message on the page that reads "Your order has been placed". However, I would like this success message to appear i ...

Search through an array, identify duplicates, and transfer them into a separate array

I am working with an array of objects containing dates and I am looking to extract objects with the same date values into a new array. Below is the code snippet. var posts = [ { "userid": 1, "rating": 4, "mood": "happy", "date": "2 ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

When using React Final Form, the onBlur event can sometimes hinder the

What is the reason that validation does not work when an onBlur event is added, as shown in the example below? <Field name="firstName" validate={required}> {({ input, meta }) => ( <div> <label>First Name</label& ...

Utilizing the fetch API in React with hooks

I'm looking to create a basic Fetch request (or axios request) and then display the results in a list. Currently, I'm utilizing useState and useEffect, although I believe there's an error in my implementation. function App() { const [to ...

Attempting to reach <p> from numerous web pages

Currently, I am working on a project where I need to extract text data from various websites. I have successfully managed to retrieve the text data using <p> tags. I would really appreciate any assistance with this task. Thank you! ...

Tips for accessing error data when throwing an Error

I am currently facing an issue with handling error cases in my React JS project. I am having trouble accessing and reading the error data within the catch block, specifically the "code" field. try { dispatch({ type: types.READ_DATA }) const response ...

Is it possible to showcase a unique date for every item that gets added to a list?

I am new to using React, so please bear with me. I want to be able to show the date and time of each item that I add to my list (showing when it was added). I am struggling to get this functionality working with my current code. Any help or explanation o ...

Position the div beneath another div using the display:grid property

I can't seem to figure out how to position a div below another div using display:grid. The div is appearing on top instead of below. The "app-bm-payment-card-item" is actually a custom Angular component. Here's the HTML file: //div wrapper < ...

Embed the div within images of varying widths

I need help positioning a div in the bottom right corner of all images, regardless of their width. The issue I am facing is that when an image takes up 100% width, the div ends up in the center. How can I ensure the div stays in the lower right corner eve ...

Tips for inheriting and overriding controller methods in AngularJS with Java as the base language:

I have a simple controller and I want to create a new controller that is very similar to it, but without copying too much code. angular.module('test').controller('parentController', parentController); parentController.$inject = [' ...