All Your Baseline Are Belong To Your Parent Element

The other day I used JavaScript to add some text to a div.  I tried everything: textContent, innerText, innerHTML.  I tried them on the div, I tried them on a child element.  Every time the text was added the div that contained it would change position.  This was frustrating because it was leading to a cascade of element position changes that moved nearby interactive elements like buttons.  The kind of stuff your users expect to stay put.  So I was thinking about adding a warning about moving buttons…  Seriously though, what’s the deal with this text node?  I could set it up so that the text is already present and an event causes the text to either be visible or not.  But now it was about the principal of the thing and I wasn’t about to let this code walk all over me and get away with it.

Here is a simple example of the ‘bad’ behavior (JSFiddle).

I went to my first line of defense against rogue code: StackOverflow.  The veterans there had dealt with this before.  They mentioned something called baseline and how using the CSS rule ‘vertical-align’ will allow us to set it and thus have control over it.  It works:

Here is a simple example of the expected behavior after the fix (JSFiddle).

textNode: You set up us the bomb.

CATS: All your baseline are belong to us.

There’re a lot of quirks related to baselines and CSS out there and there are some amazing and in-depth blog posts on them.  If you are into design and doing the best front end work possible then I would suggest doing a deep dive on it… for great justice.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s