How to Style Embedded Tweets With Custom CSS

On
Twitter logo made with garbled words.If you're an avid Twitter user and frequently embed tweets on your website or on a blog, use this simple guide to customize their appearance to not only match it with your site's design but to also divert the attention of the readers. There are several ways to embed social updates on a webpage. The popular one is using the default embed code (HTML markup) provided by the respective social media platform. Another way is to use the platform's JavaScript API for the same. Naturally, this second method is less popular among the technically challenged and is generally used by developers. And, the easiest among them all is the use of a plugin for the content management system you're using to power your website. For this tutorial, I'm assuming that you're using the very first method to embed tweets on your website. It's quite easy and only involves copy-pasting the embed code at the right place. Let's not wait further and learn how to apply different styles to the embedded tweets just with the help of custom CSS code.

Twitter logo made with garbled words.
The possibilities of customizing HTML markup are endless. We're going to show a few customization examples for your guidance and inspiration. Feel free to extend these examples or to create new styles for your embedded tweets.

Read Also:
Complete Twitter Guide for Beginners and Avid Users


Let's get started and “stylize” our embedded tweets—like a pro!

A Quick Primer for Embedding a Tweet

Let's quickly learn to embed a tweet on a webpage. Open the tweet you want to embed using the default Twitter web interface in a web browser.

One can either use the native desktop interface or the light mobile interface offered by Twitter. Both the options support tweet embedding option. Once you've opened the tweet, look for the clickable arrow to get started as shown in the image below.

Context menu with an embed tweet option.
Clicking the arrow reveals a drop-down menu which includes an Embed Tweet option. Clicking it will present the embed code along with the preview of the tweet as it may appear on the webpage.

HTML embed code for the tweet.
You can see that it's the <blockquote> HTML tag that's used to render and display the embedded tweet. After pasting the embed code at the right place, clear your web browser's cache and reload the webpage to see if the embedded tweet is appearing correctly or not!

Here's what a sample tweet embed code may look like.


<blockquote class="twitter-tweet" data-lang="en">
<p lang="en" dir="ltr">
Code refactoring is an art to deliver the same (or better) performance with a leaner muscle 💪🎫<a href="https://twitter.com/hashtag/coding?src=hash&ref_src=twsrc%5Etfw">#coding</a> <a href="https://twitter.com/hashtag/programming?src=hash&ref_src=twsrc%5Etfw">#programming</a> <a href="https://twitter.com/hashtag/frontend?src=hash&ref_src=twsrc%5Etfw">#frontend</a></p>
— Rajeev Edmonds (@rajeevedmonds) <a href="https://twitter.com/rajeevedmonds/status/786048210426994689?ref_src=twsrc%5Etfw">October 12, 2016</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

You may notice that it's not just the HTML markup but a JavaScript file is also used to render the tweet. This file is loaded in an asynchronous fashion so that it does not hamper the page load speed.

If you're embedding multiple tweets on a webpage, include this JavaScript file—just once. And, here's how the embedded tweet looks in its default state.

Embedded tweet with the default light theme.
The default light theme is good enough for most websites gelling easily within the primary content area of the webpage. So, this completes the—tweet embedding primer—paving way for the customization lessons. Let's start with the less flexible code-free way to customization.

Code-Free Global Customization Settings [Limited]

Before we dive into CSS-powered customization, let's take a quick look at some of the options available for adding quick basic styles to the embedded tweet—and that too with a site-wide effect.

In other words, the styles applied through this methodology will be effective on every single page of your website. All you need to do is to add few <meta> tags to the <head> section of your website.

Here are the <meta> tags one can use for simple customizations.


<meta name="twitter:widgets:theme" content="dark">
<meta name="twitter:widgets:link-color" content="#555fff">
<meta name="twitter:widgets:border-color" content="#22eeff">

The first tag allows you to use a light or a dark theme. Depending on your website's theme, you can choose your preferred theme. The light one is the default theme.

The second meta tag can be used to customize the hyperlink color within the embedded tweet. Use the content="" attribute of the second meta tag to supply the hexadecimal code of the desired color.

The last one is quite similar to the second one when it comes to providing the custom color value. But, this one, changes the border color of the embedded tweet. Feel free to use a color picker application for generating hex values of your desired colors.

Embedded Tweet Customization Through CSS

Now comes the real part you've been waiting for—so far! When it comes to applying custom CSS to the embedded tweets, things are not as easy as it may seem.

You cannot simply drop the required CSS into the <head> tag (inline or external stylesheet) to get things done. It'll have no effect on the embedded tweet.

Read Also:
Best Ways to Add Custom CSS to a WordPress Website


What we need is a combination of custom JavaScript and CSS. The right code placed at the right place will do the magic. And, here's a sample customized embedded tweet compared with the original one.

Customized embedded tweets
Without wasting any time, let's go for customization of the embedded tweets. Make sure you test these customizations on a demo site before transferring the code to the live website.

The CSS rules applied on a tweet entirely depend on your customization needs. The style of the sample customized tweet shown above is just for the demo purpose.


Let's start the customization process!

Problem #1: Whenever we embed a tweet in a web page, it is rendered in two different ways in the web browsers. In Firefox and Edge, the tweet is rendered through a <iframe> tag and in the browsers powered by a WebKit rendering engine viz., Chrome, Opera, and Safari, the tweet is rendered through a custom <twitterwidget> tag that uses Shadow DOM.

In simple words, the tweet is embedded in such a way that prevents the direct application of the CSS rules. So, our JavaScript code, first detects the type of browser (WebKit or non-WebKit), and then uses the relevant tweet customization code applicable to that web browser.

Problem #2: Now, there can be 3 different situations when it comes to the application of tweet customization code. These three scenarios are as follows.
  • There's NO embedded tweet on the web page.
  • There's one and only one embedded tweet on the web page.
  • There're more than one embedded tweets on the web page. Yes, here we need to explicitly apply CSS rules to each of the tweet.
Our tweet customization code needs to keep a check on these conditions (on page load) and should behave accordingly. So, here's the much-awaited code. We need to add it just before the closing </body> tag on the web page.


<script>
/*<![CDATA[*/
function customizeTweet() {

    if (document.getElementById("twitter-widget-0")) {

        var maxTweets = 10;

        for (i = 0; i < maxTweets; i++) {

            if (document.getElementById("twitter-widget-" + i)) {
                var isChromium = window.chrome;
                var winNav = window.navigator;
                var vendorName = winNav.vendor;
                var isOpera = typeof window.opr !== "undefined";
                var isIEedge = winNav.userAgent.indexOf("Edge") > -1;
                var isIOSChrome = winNav.userAgent.match("CriOS");
                var isSafari6Plus = !!navigator.userAgent.match(/safari/i) && !navigator.userAgent.match(/chrome/i) && typeof document.body.style.webkitFilter !== "undefined";
                var tweetCSS = ".EmbeddedTweet{height:auto !important}";
                var tweetStyle = document.createElement("style");

                tweetStyle.setAttribute("id", "tweet-style-" + i);
                tweetStyle.innerHTML = tweetCSS;
                tweetStyle.type = "text/css";

                if ((isIOSChrome) || (isChromium !== null && typeof isChromium !== "undefined" && vendorName === "Google Inc." && isIEedge === false) || (isOpera === true) || (isSafari6Plus)) {

                    var styleTag = document.getElementById("twitter-widget-" + i).shadowRoot;
                    styleTag.insertBefore(tweetStyle, styleTag.childNodes[0]);
                } else {

                    var tweetWidget = document.getElementById("twitter-widget-" + i).contentDocument;
                    tweetWidget.head.appendChild(tweetStyle);
                }
            } else break;
        }
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

addLoadEvent(customizeTweet);
/*]]>*/
</script>

In this code, only two things need your attention. The first one is the maxTweets variable and the second one is the tweetCSS variable.

The value 10 assigned to the variable maxTweets doesn't imply that the code is executed that number of times on each page load. Here, this value means that the code can customize up to 10 embedded tweets on a web page.

For example, if the value assigned to the variable maxTweets is 5 and there are 7 embedded tweets on a web page, only the first 5 will be customized and the last two will remain in their original form.

In case, there are 3 tweets, the code execution will automatically terminate after customizing those three embedded tweets.

Read Also:
How to Get Followers and Customers Through Twitter's Advanced Search


You can change this value as per your needs. For example, if you never embed more than 2 tweets on a single page, you can set this variable's value to two or three.

And, the second variable tweetCSS is where you'll provide all the custom CSS rules within the double quotes. If you carefully examine the provided code, you'll notice that I've included a CSS rule .EmbeddedTweet{height:auto !important} for that variable.

This CSS rule is mandatory and should not be omitted. Just after this important CSS rule, you can append your desired rules.

Note: For some of the custom CSS rules, you may need to add the !important rule to the style declaration. It's not required for every single rule.


To get you started, here are the sample CSS rules I've used for the demo tweet. Feel free to change or extend it as per your needs.


.TweetAuthor-name {
    color:#2a83e7;
}
.EmbeddedTweet {
    background-color:#f3f9f8 !important;
    border-color:#e3f5f9 !important;
    height:auto !important;
}
.Tweet-header {
    color: white;
}
.EmbeddedTweet:hover .TweetAuthor-name {
    color:#2054d4;
}
.Tweet-text {
    padding:10px;
    border-radius:5px;
    border:1px solid #ddd;
    background-color:#eee;
}

I've used only a handful of CSS classes for the customization. There are several other classes, one can use to customize different parts of the embedded tweet.

To know about these CSS classes, right-click on the embedded tweet and click on the Inspect or Inspect Element option from the context menu. A sample is shown below.

HTML code snippet
Feel free to expand the entire DOM tree to know about all the CSS classes used for the embedded tweet.

After customization, make sure to test it on some of the popular web browsers available on your computer. Do not hesitate in testing it on a smartphone as well.

So, this completes our embedded tweet customization guide. If you get stuck while implementing this solution, feel free to give me a shout for the help.