styling a flex container with aligned text and buttons

I'm attempting to align text on the left and button controls on the right within a display: flex div.

<CustomFieldContainer>
  <StyledWellContainer>
    <FieldDetails key={id}>
      <H4 bold>{label}</H4>
      <StyledBody>({capitalizeFirst(type)}) {required && <StyledSpan>REQUIRED</StyledSpan>} </StyledBody>
    </FieldDetails>
    <DeleteAction {...props} />
  </StyledWellContainer>
</CustomFieldContainer>

This is what I have achieved so far.

Below is the CSS for all the ReactJS elements mentioned above.

const CustomFieldContainer = styled.div`
  display: flex;
  flex-direction: row;
`;


const FieldDetails = styled.div`
  display: flex;
  flex-direction: column;
  border: none;
`;

const DeleteButton = styled(Button)`
  flex-basis:33.33%;
  margin-right: 0;
  margin-left:auto;
  display:block;
`;

With this setup,

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

The goal is simple, as shown below:

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

Any assistance would be greatly appreciated. The main idea is to have a container with texts on the left and controls on the right. Thank you.

Update:

const StyledWellContainer = styled(WellContainer)`
  margin-right: 1rem;
  width: 100%;
  padding-bottom: 2px;
  padding-top: 0;
`;


import styled from 'styled-components';

const WellContainer = styled.div`
  display: flex;
  flex-direction: column;
  padding: 1rem;
  border: ${({ theme, borderType }) => (borderType === 'attention' ? theme.color.border.negative : theme.color.border.light)};
  border-radius: 12px;

  & > * {
    padding-bottom: 1rem;
    margin-bottom: 1rem;
    border-bottom: ${({ theme, disableDivider }) => (disableDivider ? 'none' : theme.color.border.light)};
  }
  & > :last-child {
    padding-bottom: 0;
    margin-bottom: 0;
    border-bottom: none;
  }
`;

export default WellContainer;

Update after changes, advised by Adam.

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

Answer №1

Your StyledWellContainer needs some adjustments to its styles:

  flex: 1 0;
  display: flex;
  flex-direction: row;
  align-items: flex-start;

Currently, the container is set as a column, causing the button to appear below instead of beside the content.

Changing it to a row layout will fix this issue. The flex: 1 0 property ensures it stretches to fit the parent, while align-items: flex-start; prevents the button's content from stretching in height.

Additionally, allow the button to maintain its base size without forcing it to grow:


const DeleteButton = styled(Button)`
  flex: 0 0 auto;
  margin-right: 0;
  margin-left: auto;
`;

Answer №2

TheStyledContainer should act as the flex container instead of OtherFieldContainer

const TheStyledContainer = styled.div`
  align-items: center;
  display: flex;
  flex-direction: row;
`;

const FieldInfo = styled.div`
  display: flex;
  flex: 2;
  flex-direction: column;
  height: 100%;
  border: none;
`;

const RemoveButton = styled(Button)`
  flex: 1;
  margin-right: 0;
  margin-left:auto;
  display:block;
`;

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

Ways to prevent the :link style being applied to every link

Is there a way to apply this CSS styling to only one specific link and not all the links on my page? Here is the CSS code that is currently being applied to all links: a:visited { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 14px ...

The implementation of combineSlices in reduxjs/[email protected] is an essential feature for managing

I am struggling to figure out how to properly useAppSelector with LazyLoadedSlices: Here is the setup of my store // @shared/redux/store.ts // comment: https://redux-toolkit.js.org/api/combineSlices // eslint-disable-next-line @typescript-eslint/no-empty ...

Tips for incorporating Material.io outlined icons within css pseudoelements (::before) usage

I'm attempting to incorporate the Material.io icon into a button using ::before, but it is appearing filled rather than outlined. Unfortunately, there are no available instructions on how to display the icon in an outlined style. This is the code I ...

Equal size images displayed within cards in Material UI

Is there a way to create a list of Material UI components with images that have uniform height, even if the original images vary in size? I want to make all image heights responsive and consistent across all cards. Any suggestions on how to achieve this? ...

React - the method runs correctly when triggered by state changes, but runs twice when the parent component's state changes

As I work on constructing a page that requires data to be initialized upon mounting, updated based on responses from a websocket server triggered by a button click event, and the ability to disable and re-enable the button with a countdown for the user. M ...

Exploring the discrepancies in utilizing the i18n library versus directly incorporating locale from JSON in vue.js

Recently, I decided to incorporate Chinese language into my Vue app. To achieve this, I loaded the entire JSON text into Vuex and utilized the stored text directly, instead of relying on an i18n library. I'm curious to know if there are any potential ...

Bringing in two JavaScript files with identical names

Recently, I encountered a challenging situation. I am working with material-ui and nextjs, both of which have a module called Link that is essential for my project. import { Link } from '@material-ui/core'; However, this setup is causing compil ...

Showcasing the Google Static maps API output in a React component

Using Google's static maps API to create an image from a polyline sourced from Strava's API. Below is the code snippet: const response = await axios(`https://maps.googleapis.com/maps/api/staticmap?path=enc:${props.obj.map.summary_polyline}&si ...

What is the best way to add rounded corners to tables in Bootstrap 3?

Is there a way to give the top and bottom corners of a table rounded edges? I am currently using Bootstrap 3 tables, but they have no corner radius by default. How can I achieve this effect? ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Tips for Positioning Content in the Center of a Bootstrap Div

I'm struggling to center the jackpot-item-container div within a chart. Can anyone help me figure this out? Check out my code on CodePen. <div id="jackpot-container" class="col-sm-12"> <div id="jackpot-item-container"> <span id= ...

Whenever I attempt to use for or while loops in my application, it consistently crashes

I've recently started learning reactjs and I'm working on a simple app. I created a decrement button that should only work if the item count is greater than or equal to zero. However, when I tried using while and for loops in my code, my app cras ...

Managing the rendering of components in ReactJS based on different scenarios

I am working on a task where I need to dynamically render a specific component based on the stage scenario of the page. To achieve this, I am utilizing a variable called "transitComponent" which will render one of three components - a circular progress for ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Learn the step-by-step process of cropping and zooming an image using the react-image-crop

I am looking to implement zooming and cropping functionality for an image using react-image-crop instead of react-easy-crop. Currently, the cropping does not take into account the zoom level set by ReactCrop's scale property. I want to be able to zo ...

Is it possible to incorporate a component library built on Material UI v5 into a Material UI v4 project?

As a newcomer to Material UI, I am diving into a React project that heavily relies on React v16 and Material UI v4. We are in the process of creating a component library for this project with the intention of migrating it to Material UI v5 and React v18. ...

Encountering a "Text creation error" while trying to run a three.js demo on Microsoft Edge using the WebGL context

When attempting to run three.js on Edge, an error message appears stating 'text could not be created. Reason: Could not create a WebGL context.' Even after trying to execute the official three.js example on Edge, the same error persisted, while ...

Implementing a function in ReactJS that is activated by multiple buttons

Apologies for the unclear title. My issue revolves around having three different button tags, each of which should send a unique argument to the function selectSupplier(). However, no matter which button is clicked, only the last value ("ultramar") is be ...

When using a React Router path variable along with other paths, React may have difficulty distinguishing between them

Setting up react router in my project to differentiate between user username variables and other paths is proving challenging. For instance: baseUrl/admin baseUrl/daniel Currently, React is unable to distinguish between the two. My intention is to query ...