简体   繁体   中英

Why is text placed differently in <input>s than <span>s or <textarea>s?

I'm trying to build a jQuery plugin that fakes the HTML5 placeholder attribute (like What is the most accurate way to emulate the "placeholder" attribute in browsers that don't support it natively? ). To do this I'm inserting a <span> before the appropriate <input> or <textarea> and duplicating the styling.

Unfortunately, I've discovered that browsers magically place the text differently in <input> s than <span> s or <textarea> s, as demonstrated by http://jsfiddle.net/63zcD/1/ —the text is vertically centered in the <input> , even though Web Inspector says the styling is identical across all three. The effect appears in Safari, Chrome, and Firefox.

Tricks that haven't worked:

  • vertical-align: middle; , vertical-align: text-bottom;
  • display: inline-block;

Twitter's login page fakes the placeholder attribute, but they get around this problem by wrapping the <span> and <input> / <textarea> in a containing <div> and manually styling the <span> for a visual match, which isn't an option for a plugin that needs to run automatically.

Assigning a line-height that is equal to the element height should work. See this fork of your original fiddle, so to speak: http://jsfiddle.net/pygPs/ .

A quick browser check showed it rendering properly in IE 9, IE 6, as well as the latest Mac versions of Firefox, Chrome, and Safari. I didn't change any of the existing CSS from the original link, just added one line:

height: 26px;
line-height: 26px; /*added this line*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM