In this article, we will show you how to add custom CSS to your AMP extension. As an example, we will customize the mini-cart item counter and change its background color.
Important Information:
We strongly recommend that you make all changes to your custom AMP theme, not to the default AMP Theme One. This way you can update your AMP theme, avoiding the risk of losing your customizations.
Step 1. Create Custom AMP Theme
If you have not created your custom AMP theme yet, please follow the step-by-step guide on how to create a custom AMP theme. Otherwise, proceed to the next step.
Step 2. Add Template for CSS
Create the custom_css.phtml
file with the following content:
<?php /** @var \Magento\Framework\View\Element\Template $block */ ?>
<style amp-custom>
.basket__count-wrp {
background-color: #6600ff;
}
</style>
Here we set styles to change the background color of the mini-cart item counter. However, you can change the code for your own purposes.
Step 3. Apply Styles to Pages
At this point, you need to create a layout file to indicate to which pages you want to add the CSS. In the example below, we use the amp_default handle, which is equivalent to the default handle, to add CSS to all AMP pages.
You should create amp_default.xml
file with the following content:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="head.additional">
<referenceBlock name="ampcss">
<block name="custom.css" template="Plumrocket_AmpTheme::custom_css.phtml" after="-"/>
</referenceBlock>
</referenceBlock>
</body>
</page>
Once the styles are applied, clear the Magento cache to see the results on the frontend:
Why CSS are stored in .phtml files?
By default, the CSS are stored in the .css
files in the Magento application file system. However, due to the AMP technology requirements, we cannot add CSS files directly to AMP pages. Hence, we include CSS code within a <style amp-custom>
tag using the .phtml
files.
Additionally, we store CSS in .phtml
files to avoid compatibility issues with Magento CSS file delivery. To make it clear, the Magneto platform has its own minification and deploy system of static files that process CSS files.
Moreover, a lot of third-party vendors have Magento optimization extensions that also process CSS files and may cause some issues.