Blog › Jekyll

Placing manual AdSense units in Jekyll Chirpy safely

Fix broken Chirpy post cards and oversized mobile AdSense banners using metadata-hook.html, DOM injection, and SCSS without overriding theme layouts.

Placing manual AdSense units in Jekyll Chirpy safely

Google AdSense Auto Ads broke post cards and injected oversized mobile banners across my Jekyll Chirpy blog. This post explains how I replaced Auto Ads with three manual ad placements using only Chirpy’s official metadata-hook.html, vanilla JavaScript DOM injection, and custom SCSS—without touching any theme layouts.

Tested with Jekyll 4.4 and jekyll-theme-chirpy 7.6.

Why Auto Ads broke my Chirpy layout

Google AdSense Auto Ads look convenient at first because you only drop one <script> tag into <head>. After enabling Auto Ads on my Chirpy blog and inspecting real desktop and mobile viewports, I ran into two layout issues that hurt readability right away:

  • Broken post cards on the home page: AdSense injected ad containers between the title and summary text inside .card-wrapper, throwing off card height alignment and visual rhythm across the post feed.
  • Oversized square ads on mobile: On 375px viewports, responsive Auto Ads expanded into 375x375px squares that covered most of the initial screen and interrupted reading flow between paragraphs.

Switching to manual ad units solves both problems, but the naive Jekyll approach—copying _layouts/post.html or _includes/head.html from the gem into your repository—creates merge conflicts every time you upgrade Chirpy.

Implementation approachTheme upgrade compatibilityPlacement precisionMaintenance cost
Overriding _layouts/post.html and _includes/head.htmlLow (merge conflicts on upgrades)HighHigh
Official metadata-hook.html + JS DOM injection + SCSSHigh (theme files stay untouched)HighLow

If you already maintain a heavily forked Chirpy layout, editing _layouts/post.html directly is fine. For a gem-based Chirpy setup, keeping theme templates untouched saves far more time over multiple upgrades. I chose Chirpy’s official extension hook, _includes/metadata-hook.html, to load a small script that mounts manual slots at runtime.

Designing three viewport-aware manual ad slots

I designed three distinct placements around Bootstrap’s 768px and 1200px breakpoints so ads never crowd small screens or push main content aside.

flowchart TD
    A["DOMContentLoaded init"] --> B{"Check viewport width"}
    B -->|">= 1200px"| C["Vertical sidebar unit"]
    B -->|">= 768px"| D["In-article h2 + horizontal bottom"]
    B -->|"< 768px"| E["Bottom 320x100 slim banner"]
  • Wide desktop right sidebar (>= 1200px, vertical unit): On post pages, the ad mounts right below the table of contents (#toc-wrapper). On pages without a TOC—such as the home feed or category archives—it mounts inside #panel-wrapper below Trending Tags with position: sticky.
  • Desktop in-article units (>= 768px, fluid in-article): The script counts direct <h2> children (:scope > h2) inside article .content. Posts with 4 or more headings get one unit near the 45% mark, and long posts with 8 or more headings get a second unit near the 78% mark. Mobile viewports skip in-article ads completely to keep reading focused.
  • Post bottom unit (just before .post-tail-wrapper): Desktop viewports render a horizontal unit constrained to the article width (fullWidthResponsive: false). Mobile viewports (< 768px) render AdSense’s fixed 320x100px large mobile banner so it never balloons into a square.

Step 1: Loading the script via _includes/metadata-hook.html

Chirpy automatically includes _includes/metadata-hook.html at the end of <head>. I load the AdSense library there and gate my custom placement script behind jekyll.environment == 'production' so local jekyll serve refreshes never generate invalid ad traffic.

1
2
3
4
5
6
7
8
9
<!-- _includes/metadata-hook.html -->
<script
  async
  src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
  crossorigin="anonymous"
></script>
{% if jekyll.environment == 'production' %}
  <script defer src="{{ '/assets/js/adsense-layout.js' | relative_url }}"></script>
{% endif %}

If you have not verified your AdSense publisher script or ads.txt yet, see my earlier note on setting up Google AdSense on Jekyll Chirpy.

Step 2: Writing the DOM injection script (assets/js/adsense-layout.js)

One Chirpy detail tripped me up during initial testing: Chirpy initializes Tocbot asynchronously, populating #toc-wrapper #toc and removing the invisible class after the page paints. If you append the sidebar ad before Tocbot finishes, the unit either appears inside an invisible wrapper or sits above the TOC.

To avoid that race condition, the script watches #toc-wrapper with a MutationObserver until #toc is visible and populated, with a 1.5-second fallback timer for posts that have no headings at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// assets/js/adsense-layout.js
(function () {
  'use strict';

  var AD_CLIENT = 'ca-pub-XXXXXXXXXXXXXXXX'; // Your AdSense publisher ID
  var SLOTS = {
    sidebarVertical: '1111111111',
    inArticle: '2222222222',
    postBottom: '3333333333'
  };

  function createAdContainer(className, slotId, options) {
    var wrapper = document.createElement('div');
    wrapper.className = 'ad-slot-wrapper ' + className;
    wrapper.setAttribute('aria-label', 'Advertisement');

    var label = document.createElement('span');
    label.className = 'ad-slot-label';
    label.textContent = 'AD';
    wrapper.appendChild(label);

    var ins = document.createElement('ins');
    ins.className = 'adsbygoogle';
    ins.style.display = options.display || 'block';
    if (options.width) ins.style.width = options.width;
    if (options.height) ins.style.height = options.height;
    if (options.textAlign) ins.style.textAlign = options.textAlign;

    ins.setAttribute('data-ad-client', AD_CLIENT);
    ins.setAttribute('data-ad-slot', slotId);
    if (options.layout) ins.setAttribute('data-ad-layout', options.layout);
    if (options.format) ins.setAttribute('data-ad-format', options.format);
    if (options.fullWidthResponsive !== undefined) {
      ins.setAttribute('data-full-width-responsive', String(options.fullWidthResponsive));
    }

    wrapper.appendChild(ins);
    return wrapper;
  }

  function pushAd() {
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (e) {
      // Ignore quietly when ad blockers block adsbygoogle.js
    }
  }

  function mountSidebarAd(target, isSticky) {
    var panelWrapper = document.getElementById('panel-wrapper');
    if (!panelWrapper || panelWrapper.querySelector('.ad-slot-sidebar')) return;

    var adEl = createAdContainer(
      isSticky ? 'ad-slot-sidebar ad-slot-sidebar-sticky' : 'ad-slot-sidebar',
      SLOTS.sidebarVertical,
      { format: 'vertical', fullWidthResponsive: false }
    );
    target.appendChild(adEl);
    pushAd();
  }

  function injectSidebarAd() {
    if (!window.matchMedia('(min-width: 1200px)').matches) return;

    var panelWrapper = document.getElementById('panel-wrapper');
    if (!panelWrapper || panelWrapper.querySelector('.ad-slot-sidebar')) return;

    var tocWrapper = document.getElementById('toc-wrapper');
    if (!tocWrapper) {
      mountSidebarAd(panelWrapper, true);
      return;
    }

    var tocReady = function () {
      var tocNav = tocWrapper.querySelector('#toc');
      return !tocWrapper.classList.contains('invisible') && tocNav && tocNav.children.length > 0;
    };

    if (tocReady()) {
      mountSidebarAd(tocWrapper, false);
      return;
    }

    var settled = false;
    var observer = new MutationObserver(function () {
      if (!settled && tocReady()) {
        settled = true;
        observer.disconnect();
        mountSidebarAd(tocWrapper, false);
      }
    });
    observer.observe(tocWrapper, {
      attributes: true,
      attributeFilter: ['class'],
      childList: true,
      subtree: true
    });

    window.setTimeout(function () {
      if (!settled) {
        settled = true;
        observer.disconnect();
        mountSidebarAd(tocReady() ? tocWrapper : panelWrapper, !tocReady());
      }
    }, 1500);
  }

  function injectPostAds() {
    var content = document.querySelector('article .content');
    var tailWrapper = document.querySelector('.post-tail-wrapper');
    if (!content || !tailWrapper) return;

    var isDesktop = window.matchMedia('(min-width: 768px)').matches;

    if (isDesktop) {
      var headings = Array.prototype.slice.call(content.querySelectorAll(':scope > h2'));
      var insertIndices = [];
      if (headings.length >= 4) insertIndices.push(Math.floor(headings.length * 0.45));
      if (headings.length >= 8) {
        var secondIdx = Math.floor(headings.length * 0.78);
        if (secondIdx > insertIndices[0] + 1) insertIndices.push(secondIdx);
      }

      insertIndices.forEach(function (idx) {
        var targetH2 = headings[idx];
        if (!targetH2 || !targetH2.parentNode) return;
        var inArticleAd = createAdContainer('ad-slot-in-article', SLOTS.inArticle, {
          layout: 'in-article',
          format: 'fluid',
          textAlign: 'center'
        });
        targetH2.parentNode.insertBefore(inArticleAd, targetH2);
        pushAd();
      });
    }

    if (!document.querySelector('.ad-slot-post-bottom')) {
      var bottomOptions = isDesktop
        ? { format: 'horizontal', fullWidthResponsive: false }
        : { display: 'inline-block', width: '320px', height: '100px' };

      var bottomAd = createAdContainer(
        isDesktop ? 'ad-slot-post-bottom' : 'ad-slot-post-bottom ad-slot-post-bottom-mobile',
        SLOTS.postBottom,
        bottomOptions
      );
      tailWrapper.parentNode.insertBefore(bottomAd, tailWrapper);
      pushAd();
    }
  }

  function init() {
    window.requestAnimationFrame(function () {
      injectSidebarAd();
      injectPostAds();
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Step 3: Styling the containers in assets/css/jekyll-theme-chirpy.scss

On long posts with 10+ headings, the TOC can grow tall enough to push the sidebar ad completely off the viewport. Capping #toc-wrapper #toc at max-height: 42vh with internal scrolling keeps both the active heading and the sidebar ad visible on desktop screens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* assets/css/jekyll-theme-chirpy.scss */
.ad-slot-wrapper {
  position: relative;
  text-align: center;
}

.ad-slot-label {
  display: block;
  margin-bottom: 0.35rem;
  font-size: 0.65rem;
  font-weight: 600;
  letter-spacing: 0.08em;
  color: var(--text-muted-color);
  opacity: 0.65;
  text-align: left;
  user-select: none;
}

.ad-slot-sidebar {
  display: none;
}

@media (min-width: 1200px) {
  #toc-wrapper #toc {
    max-height: 42vh;
    overflow-y: auto;
  }

  .ad-slot-sidebar {
    display: block;
    width: 100%;
    max-width: 247px;
    margin-top: 1.5rem;
    padding-left: 1rem;
  }

  .ad-slot-sidebar-sticky {
    position: sticky;
    top: 2rem;
    padding-left: 0;
  }
}

.ad-slot-in-article {
  margin: 2rem 0;
  padding: 0.75rem 0;
  border-top: 1px solid var(--border-color);
  border-bottom: 1px solid var(--border-color);
}

.ad-slot-post-bottom {
  margin: 2.25rem 0 1.25rem;
  padding-top: 0.75rem;
  border-top: 1px solid var(--border-color);
}

.ad-slot-post-bottom-mobile {
  margin: 1.5rem 0 1rem;
  text-align: center;
}

.ad-slot-post-bottom-mobile .ad-slot-label {
  max-width: 320px;
  margin-left: auto;
  margin-right: auto;
}

Production pitfalls and AdSense policy rules

1. Calling push({}) on a hidden <ins> triggers availableWidth=0

If you hide .ad-slot-sidebar with display: none on < 1200px screens but still append <ins class="adsbygoogle"> and call push({}), AdSense throws a runtime console error:

1
TagError: adsbygoogle.push() error: No slot size for availableWidth=0

A display: none container reports a width of 0. Always check window.matchMedia('(min-width: 1200px)').matches in JavaScript before creating the DOM node or calling pushAd().

2. Never crop ads with overflow: hidden

Warning: Applying max-height: 100px; overflow: hidden; to a parent container to clip an oversized responsive ad violates Google AdSense’s ad modification and obscuring policies.

Instead of cropping with CSS, request the right size upfront using an official fixed slot (display: inline-block; width: 320px; height: 100px) or data-full-width-responsive="false".

3. Production-only script gating

Gating adsense-layout.js with {% if jekyll.environment == 'production' %} ensures the manual units only render when GitHub Actions builds with JEKYLL_ENV="production". That protects your account from repeated local preview reloads while keeping local editing clean.

Verification checklist

Before deploying manual AdSense changes to production, run through these four checks:

  • Confirm Auto Ads are turned off in the AdSense console so manual and automatic units don’t stack on top of each other.
  • Verify at 390px, 768px, and 1440px in DevTools that no availableWidth=0 console errors appear.
  • Check that long posts scroll #toc-wrapper #toc cleanly without pushing the sidebar ad off-screen.
  • Confirm adsense-layout.js is absent in local jekyll serve HTML and present in JEKYLL_ENV=production builds.

For Google’s exact rules on modifying responsive ad tags, check the official AdSense documentation.

If you find that our responsive ad code doesn't do everything you need, you may modify your ad code to better meet the requirements of your responsive site. The examples in this article show you how
This post is licensed under CC BY 4.0 by the author.