How to Scale reCAPTCHA Responsively

Posted in Developers

Google’s latest version of reCAPTCHA (also known as “No CAPTCHA”) is a lot easier on users. For developers, though, there’s a catch. You can’t style it.

The code injects itself using a protected iframe element, preventing any CSS styling changes. The main problem with this is not being able to change the size of the reCAPTCHA widget, which is fixed at 304 pixels wide as of this writing.

One solution is to scale it according the size of its containing element. That’s what I’m going to show you in this short tutorial.

Demo

Technique

We’re going to use the CSS3 “scale” transform to uniformly scale the element.

CSS Setup

Prepare the reCAPTCHA element’s styles by setting the transform origin to its top left.

.g-recaptcha {
  transform-origin: left top;
}

Scaling with JavaScript

JavaScript is necessary because we need to update the reCAPTCHA’s scaling both when the document is ready and whenever the user resizes the page.

The following script includes a scaling function, which calculates and applies the CSS transform by inserting a style attribute on the reCAPTCHA element.

After that, the script inside $(function() { runs when the document is ready. It runs the scaleCaptcha function once initially, and sets up a window resize handler that runs the scaleCaptcha function when the window is resized.

If copy & pasting this code, replace the .container selector with your own containing element’s selector.

For this example to work, you’ll need jQuery and the jQuery Throttle/Debounce plugin included in your page.

// Resize reCAPTCHA to fit width of container
// Since it has a fixed width, we're scaling
// using CSS3 transforms
// ------------------------------------------
// captchaScale = containerWidth / elementWidth

function scaleCaptcha(elementWidth) {
  // Width of the reCAPTCHA element, in pixels
  var reCaptchaWidth = 304;
  // Get the containing element's width
	var containerWidth = $('.container').width();
  
  // Only scale the reCAPTCHA if it won't fit
  // inside the container
  if(reCaptchaWidth > containerWidth) {
    // Calculate the scale
    var captchaScale = containerWidth / reCaptchaWidth;
    // Apply the transformation
    $('.g-recaptcha').css({
      'transform':'scale('+captchaScale+')'
    });
  }
}

$(function() { 
 
  // Initialize scaling
  scaleCaptcha();
  
  // Update scaling on window resize
  // Uses jQuery throttle plugin to limit strain on the browser
  $(window).resize( $.throttle( 100, scaleCaptcha ) );
  
});

If you want to see the script in action, check out the Demo on CodePen. Let me know if you have any questions/comments using the comments below.

← Back to Blog Index

Comments

Leave a Reply

← Back to Blog Index