Home > Software design >  Align <a> to right side of div
Align <a> to right side of div

Time:12-03

How would I align the <a> element, containing the Button with the string Push Me to the right side of the <div> (<Paper>)?

https://codesandbox.io/s/eager-noyce-j356qe

The application is in ´demo.tsx` file.

Note: I cannot set the position of the button to absolute and then position it right: 0px because I need to adjust the height of the <div> (<Paper>) according to its content, which includes the height of the <Button>.

CodePudding user response:

Based on your demo i'd suggest you'd wrap the text in a <div> and give display: flex property for your <Paper>. Then you could use flex-gow: 2 on that div

<Paper style={{ display: 'flex' }}>
  <div style={{ flexGrow: '2' }}>
    <p>This is some text </p>
    <p>This is even more text </p>
  </div>
  <Link
    component="button"
    variant="body2"
    onClick={() => {
      console.info("I'm a button.");
    }}
  >
    <Button
      variant='contained'>
      Push Me
    </Button>
  </Link>
</Paper>

Here's the forked Codesandbox

More about flexbox if you're not familiar with it

CodePudding user response:

To align an element to the right side of a container, you can use the text-align: right CSS property on the container element. This will align all of the elements inside the container to the right side.

In your case, you can add the text-align: right property to the element, which will align the element (which contains the ) to the right side of the element.

Here is an example of how you could do this:

import * as React from 'react';
import { Paper, Button } from '@material-ui/core';

function Demo() {
  return (
    <Paper style={{ textAlign: 'right' }}>
      <a href="#">
        <Button variant="contained">Push Me</Button>
      </a>
    </Paper>
  );
}

In this code, the textAlign: 'right' property is added to the style attribute of the element, which aligns the element (and the inside it) to the right side of the element.

Note that you can also use the className attribute of the element to apply a CSS class that contains the text-align: right property, instead of adding the property directly to the style attribute. This can help keep your React components clean and separate the styles from the component logic.

  • Related