Magento – Theme: Best practices

Magento theme

Magento is a powerful and popular e-commerce platform that offers a wide range of features and functionalities. To make the most out of this platform, it is important to follow some best practices that can enhance the performance, security, and user experience of your Magento 2 store.

Partnering with an experienced Adobe Commerce agency can also help you implement these best practices and optimize your store for success.

Understanding the Theme in Magento2

In Magento 2, a theme is a collection of files that determines the visual appearance of your online store. It includes templates, layout files, CSS, JavaScript, and other assets that define the look and feel of your website. Magento theme play a crucial role in creating a unique and engaging user experience for your customers. One of the key features of Magento 2 is its flexibility in theme customization.

Directory Structure of Magento Themes

A proper theme file structure is a fundamental aspect of adhering to best practices in theme development for platforms like Magento. A well-organized file structure contributes to several benefits like Readability and Maintainability, Modularity, Scalability, Customization and Overrides, Consistency, Ease of Updates, Performance, etc.

Magento Theme File Structure

What are the best practices for working with Magento themes?

Best practices for Magento themes are important because they ensure that your online store operates smoothly and efficiently.

Recommended reading 7  Common Pitfalls to avoid while Developing a eCommerce Magento Website

As a developer, adherence to best practices while working with Magento themes is crucial for several reasons:

1. Scalability: Following best practices ensures that your theme is scalable, meaning it can handle growth and increased demand without a significant loss in performance. 

2. Performance: Magento is a robust e-commerce platform, but poorly optimized themes can negatively impact performance. Faster websites often lead to higher conversion rates and improved search engine rankings.

3. Compatibility: Magento themes need to be compatible with different browsers, devices, and screen sizes. Following best practices ensures cross-browser compatibility and responsiveness, making your online store accessible to a broader audience.

4. Security: Magento regularly releases security updates, and it’s important to stay informed about these updates and implement them in your theme to address potential vulnerabilities.

5. Maintainability: Well-organized and structured code makes your theme easier to maintain. Following best practices encourages modular and clean coding practices, making it simpler to troubleshoot issues, implement updates, and add new features to your Magento theme in the future.

6. Upgradability: Magento periodically releases new versions with improvements, features, and security patches. Following best practices ensures that your Magento theme is compatible with these updates, making it easier to upgrade your store to the latest Magento version without encountering significant compatibility issues.

7. Community Support: Following best practices aligns your theme development with established standards, making it easier to seek help and collaborate with the Magento community. You can leverage community resources, forums, and documentation more effectively when your theme adheres to widely accepted practices.

8. User Experience: A well-designed and optimized theme contributes to a positive user experience. Following best practices in theme development ensures that your online store is visually appealing, user-friendly, and capable of meeting the expectations of modern e-commerce consumers. For more information recommended to visit 7 Tips on How to Improve the UX/UI Design of a Web Application

Here are some best practices for working with Magento themes:

1. Use a Child Theme: Always use a child theme when making modifications. This ensures that your changes won’t be lost when updating the parent theme.

2. Keep It Simple: Avoid adding unnecessary complexity to your theme. The more complex it is, the harder it will be to maintain and troubleshoot.

3. Optimize Images: High-resolution images can slow down your site. Always optimize images for the web to ensure your site loads quickly.

4. Test on All Devices: Make sure your theme looks and works well on all devices. This includes desktop computers, laptops, tablets, and smartphones.

5. Follow Magento Coding Standards: Following Magento’s coding standards ensures that your theme is compatible with the Magento platform and can help prevent conflicts with other themes or extensions.

Theme development best practices

Having explored the fundamental concepts of Magento theme best practices thus far, it’s time to delve into the code and witness firsthand how implementing these principles transforms us into adept developers. Let’s navigate through the intricacies of the codebase, discovering how minor adjustments can elevate our skills and make a significant impact on our development prowess.

We recommend using the following best practices when developing themes:

  1. Less files: While working with child themes, it is advisable to extend the default styles rather than overriding them. Whenever possible, place your customizations in the _extend.less or _theme.less file instead of directly overriding a .less file from the parent theme.
  2. XML / Layout files: Customize or create new .xml layout files instead of modifying and overriding .phtml templates. For instance, when creating a new container, it is preferable to add an .xml file rather than overriding an existing template. Some other customizations that can be performed using layout instructions include:
    1. Change the position of a block or container using <move>.
    2. Add or remove a block or container by setting the remove or display attribute to true or false within the
      <referenceBlock>/<referenceContainer>.
    3. Change the HTML tag or CSS class for the existing container using the <referenceContainer> element.
    4. Add fonts, images, and JavaScript files in the <theme_dir>/web/ directory.
<page xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:View/Layout/etc/page_configuration.xsd”>
    <body>
        <!– Example 1: Create a new container –>
        <referenceContainer name=”content”>
            <container name=”custom.container” htmlTag=”div” htmlClass=”custom-container” after=”-“>
                <!– Add your custom content or blocks here –>
                <block class=”Magento\Framework\View\Element\Template” name=”custom.block” template=”YourVendor_YourTheme::custom_block.phtml”/>
            </container>
        </referenceContainer>

        <!– Example 2: Remove an existing block –>
        <referenceBlock=”catalog.product.related” remove=”true” />

        <!– Example 3: Move an existing block to a new position –>
        <move element=”catalog.product.related” destination=”custom.container” after=”-“/>
    </body>
</page>
  1. Configure Theme Properties: Utilize <theme_dir>/etc/view.xml to modify image types or sizes, or add your own types, instead of using CSS or inline methods.

Location in theme folder :

Magento Theme
  1. i18n: If you need to modify the wording in the user interface, consider adding custom CSV dictionary files instead of overriding .phtml or .html templates.

Location in theme folder :

Magento Theme

Sample code:

"Now Shopping by","Shopping by"
  1. CSS critical path: Utilize the CSS critical path to significantly enhance the page rendering speed.
  2. Always keep the text translatable: To ensure text used within your templates can be translated, wrap it within the translate function: 

Example:

For .phtml

<a href="#"><?= __('Click to download'); ?></a>

For .html (Knockout view file)

<span translate="'Out of stock'"></span>

For .js 

$t('Add to Cart');
  1. Adopt the mobile-first approach when inheriting Blank or Luma themes.
  2. Avoid redundant work in styling; instead, create a class or mixin and call them when needed.
  3. When styling a custom module, incorporate the styling within the module itself rather than adding it to the design theme. This ensures that the style is only loaded when the module is called. For example, in
    app/code/<Vendor>/<Module>/view/frontend/web/css/source/_module.less.
  4. When styling a custom theme, place styles in separate .less files instead of appending them to a single file. This approach makes styles easier to track down and debug.

As a reference, check

[Magento_Blank_Theme_Path]/web/css/_styles.less:
// Global lib
@import 'source/lib/_lib.less';
// Theme styles
@import 'source/_sources.less';
// Components styles (modal/sliding panel)
@import 'source/_components.less';

Responsive web design:

Responsive web design (RWD), also referred to as responsive design, customizes websites to provide an optimal viewing experience across diverse devices, ranging from large, high-resolution desktop monitors to mobile phones. It also holds significant importance in adhering to theme best practices.

Breakpoints are incorporated into the CSS code to establish the screen width threshold at which the design transitions from the mobile to the desktop version.

Here are the default breakpoints utilized by Blank and Luma themes, Magento’s default themes:

  • @screen__xxs: 320px
  • @screen__xs: 480px
  • @screen__s: 640px
  • @screen__m: 768px 
  • @screen__l: 1024px
  • @screen__xl: 1440px

These default values can be found in

lib/web/css/source/lib/variables/_responsive.less.

We have the flexibility to modify default values or introduce new breakpoints based on our specific needs.

Media queries:

Magento 2 is designed to support responsive web design out of the box. One of the ways to enhance the responsiveness of your theme is by utilizing media queries in your CSS. 

The styles for the Blank and Luma themes in Magento are constructed based on the UI library, which leverages CSS3 media queries, an extension of the @media rule, to adapt the layout according to screen width. 

The UI library adopts a method that involves separating style groups with @media-common and utilizing .media-width() mixins. While these mixins can be used multiple times in any .less file within a theme, they are invoked only once in

lib/web/css/source/lib/_responsive.less.

In Magento theme, the styles for mobile and desktop are defined in separate files:

  • styles-l.less is utilized to generate styles specifically tailored for desktop screens, typically with widths greater than 768px.
  • styles-m.less is employed to generate fundamental and mobile-specific styles, typically for screens with widths of 768px or less.

Let’s explore a few examples of media queries:

To ensure that Less styles rules are compiled into styles-m.css and applied to all screen widths, without the need for a media query, consider utilizing the @media-common style group separation.

//
//  Common Styles
//  _____________________________________________
& when (@media-common = true) {
  // your code
}

The .media-width() mixin is utilized for grouping style rules within specific media queries.

.media-width(<@extremum>, <@break>);

@extremum: Determines whether to use min-width or max-width in the media query condition. 

Values: min | max

@break:Defines the value of the breakpoint to compare within the media query condition.

Values: While any number can be chosen, adhering to best practices suggests utilizing default breakpoints or adding custom breakpoints as needed.

For Mobile specific styles:

//
//  Mobile Styles
//  _____________________________________________
.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__s) {
  // Styles will be applied to mobile devices with a maximum width of 640px.
  // your code
}

.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__m) {
  // Styles will be applied to mobile devices with a maximum width of 768px.
  // your code

}

& when (@media-target = 'mobile'), (@media-target = 'all') {
  @media only screen and (max-width: 475px) {
      // Styles will be applied to mobile devices with a maximum width of 475px.
  }
}

For Tablet specific styles:

//
//  Tablet Styles
//  _____________________________________________
& when (@media-target = 'desktop'), (@media-target = 'all') {
  @media only screen and (min-width: @screen__m + 1) and (max-width: (@screen__xl - 1)) {
      // styles for breakpoint > 768px and < 1440px
  }
}

For Desktop specific styles:


//
//  Desktop Styles//  _____________________________________________
.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) {
  // Styles will be applied to desktop devices with a minimum width of 768px.
  // your code
}
.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__l) {
  // Styles will be applied to desktop devices with a minimum width of 1024px.
  // your code
}
.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__xl) {
  // Styles will be applied to desktop devices with a minimum width of 1440px.
  // your code
}

Previous tutorial

Author



Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

Join 40,000+ Magento pros who receive eCommerce insights, tips, and best practices.

Request PWA Demo