RickyAYoder
RickyAYoder

Reputation: 991

How do you overlay text perfectly from a textarea onto div with same text?

I'm looking to overlap the same texts right on top of each other for an interesting idea I had on syntax highlighting.

I'm trying to do it with the textarea in the foreground, and the div in the background. After setting the same position of the elements as well as the same font size, they still do not overlap perfectly. What am I missing, exactly?

Fiddle

div,textarea{
position:absolute;
top:0;
left:0;
background:transparent;
font-size:1em;
line-height:1em;
}

Upvotes: 1

Views: 3990

Answers (3)

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

Try setting the font-family, padding, and border-width explicitly:

div,textarea{
    position:absolute;
    top:0;
    left:0;
    background:transparent;
    font-size:1em;
    line-height:1em;
    font-family:sans-serif;
    padding:0;
    border-width:0;
}

Two comments:

  1. Browsers define a default style for textarea elements, so the trick is to figure out what properties are being set by the browser and override those explicitly. It's best to override the properties on both the div and the textarea. If you only change the div to accommodate for the browser's default style of the textarea, you'll get varying results in different browsers. For example, in Chrome the default border width for a textarea is 1 pixel, while in Firefox, it's 2 pixels.
  2. Due to the way font anti-aliasing works, you'll always get a slightly bold effect. Probably best to set one of the two font colors to white or transparent.

Upvotes: 3

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

set a same font-family for both

textarea has 1px border so you can add border:1px solid transparent to div which has the text so that it aligns

* {
  margin: 0;
  padding: 0;
}
div{
    border:1px solid transparent
}
div,
textarea {
  position: absolute;
  top: 0;
  left: 0;
  background: transparent;
  font-size: 1em;
  line-height: 1em;
  font-family: arial;
}
<div>Hello, world!</div>
<textarea>Hello, world!</textarea>

Upvotes: 4

Mukul Kant
Mukul Kant

Reputation: 7122

Try this :-

Link

div,textarea{
    position:absolute;
    top:0;
    left:0;
    background:transparent;
    font-size:1em;
    line-height:1em;
    font-family:arial /*add same font-family */
}

and

 div{
   padding:3px 3px 0
  }

Upvotes: 1

Related Questions