IamGuest IamGuest - 14 days ago 7
CSS Question

Aligning a <p> tag in top right corner of <textarea>?

I have a small textarea on my page. With it, I have a

<p>
tag that says "HTML". What I want to do is align that
<p>
tag to the top right corner of the textarea, so users will know that this textarea shows HTML code. However, all my attempts have placed the
<p>
tag in the top right corner of the page.

<div id="mycode">
<p id="htmltag">HTML</p>
<textarea id="htmlcode" style="background-color: #1e1e1e; color: #ffff66;">
This is my HTML code
</textarea>
</div>


I am now also willing to use Javascript, but no Jquery.

Answer

Fairly simple to do. Just set your wrapper to be relatively positioned, then you can absolutely position your label inside the wrapper.

As @Optimae suggested, here is some CSS which also prevents the html code from being obscured by your label.

#mycode {
  position: relative;
  width: 300px;
  background: #fff;
  border: 1px solid rgb(169, 169, 169);
}

#htmltag {
  position: absolute;
  top: 0;
  right: 0;
  padding: 0;
  margin: 0;
}

#htmlcode {
  border: 0;
  padding: 0;
  width: 100%;
  max-width: 100%;
  height: calc(100% - 1.2em);
  margin-top: 1.2em; /* prevents the code from going behind the label */
  outline: none; /* Prevents blue outline when focused */
}
<div id="mycode">
   <p id="htmltag">HTML</p>
   <textarea id="htmlcode">
      This is my HTML code
      
      With some more
      text
      to 
      force 
      scrolling
   </textarea>
</div>