cyberangles blog

How to Center Align Chart Title in Google Charts: Fix for Missing Positioning Options

Google Charts is a powerful, free tool for creating interactive and visually appealing charts (e.g., bar, line, pie, scatter) for web applications. Its simplicity and integration with Google services make it a go-to choice for developers and data analysts. However, one common frustration among users is the lack of built-in options to align chart titles—by default, titles are left-aligned, and there’s no native setting in the Google Charts API to center (or right-align) them.

This can be a problem for design consistency, especially when charts need to match brand guidelines or page layouts that require centered headings. In this blog, we’ll demystify how to center-align chart titles in Google Charts using practical workarounds, even without official positioning options. We’ll cover step-by-step methods, code examples, and troubleshooting tips to ensure your charts look polished and professional.

2025-12

Table of Contents#

  1. Understanding the Problem: Why Centering Titles is Tricky
  2. Prerequisites
  3. Method 1: Center Align with CSS (Simplest Approach)
  4. Method 2: Center Align with JavaScript (Dynamic Control)
  5. Troubleshooting Common Issues
  6. Conclusion
  7. References

Understanding the Problem: Why Centering Titles is Tricky#

Google Charts renders charts as Scalable Vector Graphics (SVG), a vector image format used for graphics on the web. When you define a title using the title option in the chart’s configuration, Google Charts automatically generates an SVG <text> element for the title. By default, this element is styled with:

  • text-anchor: start (left-aligned).
  • A fixed x position (e.g., x="0"), placing it at the left edge of the chart area.

The Google Charts API does not expose a direct configuration option (like titlePosition: 'center') to modify this alignment. To center the title, we need to manually adjust the SVG <text> element’s attributes or styles after the chart is rendered.

Prerequisites#

Before we dive into the solutions, ensure you have:

  • Basic knowledge of HTML, CSS, and JavaScript: You’ll need to modify styles and write simple scripts.
  • A Google Charts project set up: Include the Google Charts library in your HTML (via the official CDN).
  • A chart with a title: Define a title using the title property in your chart’s options object (e.g., options: { title: 'Monthly Sales' }).

Method 1: Center Align with CSS (Simplest Approach)#

The easiest way to center-align a Google Charts title is to target the SVG <text> element responsible for the title using CSS. Here’s how:

Step 1: Inspect the Chart to Identify the Title Element#

First, render your chart and inspect the title element to find its class or attributes.

  1. Open your page in a browser (Chrome, Firefox, etc.).
  2. Right-click the chart title and select "Inspect" to open DevTools.
  3. In the Elements tab, locate the <text> element for the title. It typically has a class like google-visualization-title (this class is consistent across most Google Chart types).

Step 2: Add CSS to Center the Title#

Once you’ve identified the title’s class, use CSS to override its alignment. The key SVG properties to adjust are:

  • text-anchor: middle: Centers the text relative to its x position.
  • x: Sets the horizontal position (use 50% to center relative to the chart’s width).

Example Code#

Here’s a complete HTML example with a bar chart and CSS-centered title:

<!DOCTYPE html>
<html>
<head>
  <title>Center Align Google Chart Title</title>
  <!-- Load Google Charts -->
  <script src="https://www.gstatic.com/charts/loader.js"></script>
 
  <style>
    /* Target the Google Charts title element */
    .google-visualization-title {
      text-anchor: middle !important; /* Center text horizontally */
      x: 50% !important; /* Position title at 50% width of the chart */
      font-size: 18px; /* Optional: Adjust title size */
      font-weight: bold; /* Optional: Make title bold */
    }
  </style>
</head>
<body>
  <!-- Chart container -->
  <div id="salesChart" style="width: 800px; height: 400px;"></div>
 
  <script>
    // Load the Google Charts library and draw the chart
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
 
    function drawChart() {
      // Sample data
      const data = google.visualization.arrayToDataTable([
        ['Month', 'Sales'],
        ['Jan', 1000],
        ['Feb', 1200],
        ['Mar', 900],
        ['Apr', 1500]
      ]);
 
      // Chart options (include a title)
      const options = {
        title: 'Monthly Sales Report 2024', // Title to center
        width: 800,
        height: 400,
        bars: 'vertical' // Bar chart type
      };
 
      // Draw the chart
      const chart = new google.visualization.BarChart(document.getElementById('salesChart'));
      chart.draw(data, options);
    }
  </script>
</body>
</html>

How It Works#

  • The CSS selector .google-visualization-title targets the title’s <text> element.
  • text-anchor: middle ensures the text is centered relative to its x coordinate.
  • x: 50% positions the title at the horizontal midpoint of the chart’s SVG container.

Notes#

  • Class Consistency: The google-visualization-title class is used for titles in most core charts (bar, line, pie, column). For specialized charts (e.g., timeline), verify the class via inspection.
  • !important Flag: Use !important to override inline styles generated by Google Charts (SVG elements often have inline style attributes that take priority).

Method 2: Center Align with JavaScript (Dynamic Control)#

If CSS alone doesn’t work (e.g., if the title’s position is dynamically updated by Google Charts), use JavaScript to modify the SVG element after the chart renders. This method ensures the title is centered even if the chart resizes or redraws.

Step 1: Use the Chart’s ready Event#

Google Charts triggers a ready event when the chart finishes rendering. We’ll use this event to modify the title element after it exists in the DOM.

Step 2: Select and Modify the Title Element#

In the ready event handler, select the title element (using its class or tag) and adjust its text-anchor and x attributes.

Example Code#

Here’s how to implement this for a line chart:

<!DOCTYPE html>
<html>
<head>
  <title>Center Title with JavaScript</title>
  <script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
  <div id="revenueChart" style="width: 800px; height: 400px;"></div>
 
  <script>
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
 
    function drawChart() {
      const data = google.visualization.arrayToDataTable([
        ['Year', 'Revenue'],
        ['2020', 10000],
        ['2021', 15000],
        ['2022', 12000],
        ['2023', 20000]
      ]);
 
      const options = {
        title: 'Annual Revenue Growth',
        width: 800,
        height: 400,
        curveType: 'function' // Line chart with curved lines
      };
 
      const chart = new google.visualization.LineChart(document.getElementById('revenueChart'));
 
      // Listen for the 'ready' event to modify the title
      google.visualization.events.addListener(chart, 'ready', function() {
        // Select the title element
        const titleElement = document.querySelector('.google-visualization-title');
        
        if (titleElement) {
          // Set alignment attributes
          titleElement.setAttribute('text-anchor', 'middle');
          titleElement.setAttribute('x', '50%');
        }
      });
 
      // Draw the chart
      chart.draw(data, options);
    }
  </script>
</body>
</html>

How It Works#

  • The google.visualization.events.addListener method attaches a callback to the chart’s ready event, ensuring the title element exists before modification.
  • document.querySelector('.google-visualization-title') selects the title element.
  • setAttribute('text-anchor', 'middle') and setAttribute('x', '50%') apply the same alignment logic as the CSS method but dynamically.

Advantages#

  • Dynamic Updates: If the chart is redrawn (e.g., on window resize), the ready event will re-run, re-centering the title.
  • Fallback for CSS Issues: Useful if the google-visualization-title class changes or if CSS selectors are blocked by CSP (Content Security Policy).

Troubleshooting Common Issues#

Issue 1: CSS Selector Not Targeting the Title#

  • Problem: The CSS doesn’t affect the title.
  • Fix: Ensure the selector matches the title’s class. If google-visualization-title doesn’t work, inspect the element to find the correct class (e.g., chart-title for custom charts).

Issue 2: Title Centers Initially but Moves on Resize#

  • Problem: The title is centered on load but shifts when the window resizes.
  • Fix: Use the JavaScript method with the ready event, as it re-runs when the chart redraws. Alternatively, add a resize listener to re-apply CSS.

Issue 3: Multiple Charts on One Page#

  • Problem: CSS centers titles for all charts, but you want only one centered.

  • Fix: Target the title of a specific chart by combining the chart’s container ID with the title class. For example:

    /* Center title only for the chart with ID 'salesChart' */
    #salesChart .google-visualization-title {
      text-anchor: middle !important;
      x: 50% !important;
    }

Conclusion#

While Google Charts lacks a native "center title" option, centering titles is achievable with CSS or JavaScript workarounds. The CSS method is simplest for static charts, while JavaScript ensures dynamic alignment (e.g., on resize). By targeting the SVG <text> element and adjusting text-anchor and x properties, you can ensure your chart titles align perfectly with your design needs.

Experiment with both methods to find what works best for your use case, and always verify the title element’s class via inspection to handle edge cases.

References#