Search code examples
htmlcssflexboxtextarea

Flexbox: can't put textarea on a new line


I am trying to float a preformatted block of text to the right of a page, keeping the text aligned to the left of the block so that I get a right-aligned paragraph containing left-justified text. This works quite well:

<html>
<head>
  <style>
    pre {
      display: flex;
      justify-content: flex-end;
      text-align: left;
    }
  </style>
</head>
<body>
  <pre>
    A preformatted para with
    various stuff
    inside it.
  </pre>
</body>
</html>

The problem is that when I add a textarea to this (for example, inserting <textarea>foo</textarea> after the first line of the <pre> para), the line breaks before and after the textarea are ignored.

It works when I wrap the <pre> in a <div> and then apply the style to the <div>:

<html>
<head>
  <style>
    div {
      display: flex;
      justify-content: flex-end;
      text-align: left;
    }
  </style>
</head>
<body>
<div>
  <pre>
    A preformatted para with a
    <textarea>textarea</textarea>
    and other stuff
    inside it.
  </pre>
</div>
</body>
</html>

but unfortunately the HTML is not under my control, so I can't do this. I could do this with a table if I was able to control the HTML; and I can't find a way to do it with float:right because the surrounding text appears alongside the floated para.

Is there any way to make this work as I had expected, changing only the CSS?

Edit: here are some images, using the code shown above:

The original code: The original code

After adding a textbox: After adding a textbox

The desired effect using an enclosing div: The desired effect using an enclosing div


Solution

  • Rather than using flexbox to shift the pre element, just use a margin.

    pre {
      margin-inline-start: auto; /* or margin-left if you prefer */
      width: fit-content;
    }
      <pre>
        A preformatted para with a
        <textarea>foo</textarea>
        and various stuff
        inside it.
      <pre>