Looking to create a responsive image in a liquid file on Shopify

Recently, I added a new feature to my Shopify backend where users can upload images to a page. While I can see the images on the front-end, they are currently aligned to the right. My goal is to make these images responsive by default and expand to fit the width of the screen.

Here is the code from my "image.liquid" file:

{%for block in section.blocks %}
    
   {{ block.settings.image_1 | img_url: "1250x" | img_tag }}

{% endfor %}
{% schema %}
  {
  "name": "Images_N",
  "blocks" : [ 
    {
      "type" : "image",
        "name" : "Image block",
        "settings": [
                        {
                              "type": "image_picker",
                              "id": "image_1",
                              "label": "Images_N"    
                        }
                    ] 
    }
        
    ],
    "presets" : [
                {
                  "category" : "image",
                  "name"  : "Images_N"
                }
    ]
  
}
{% endschema %}


And here is the code from my "product.aplustemplate.liquid" file:

{% section 'product-template' %}
{% section 'image' %}

If you'd like to view the product with this template applied, you can visit this link. My aim is to ensure the images on this page are fully responsive.

Answer №1

If you want a responsive image that spans the entire width of the screen, here is a method to achieve that:

<style>
  .media {
    display: block;
    position: relative;
    overflow: hidden;
  }

  .media > img {
    display: block;
    max-width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    object-fit: cover;
    object-position: center center;
  }
</style>

{%- for block in section.blocks -%}
  <div class="media" style="padding-bottom: {{ 1 | divided_by: block.settings.image_1.aspect_ratio | times: 100 }}%;">
    {{ block.settings.image_1 | image_url: width: block.settings.image_1.width | image_tag: loading: 'lazy', widths: '450, 660, 900, 1320, 1800, 2136, 2400, 3600, 7680', sizes: '100vw' }}
  </div>
{%- endfor -%%}
  • You should ideally place the style in a separate css file.
  • The padding-bottom on the div.media ensures the block fills the screen width while maintaining the image's aspect ratio.
  • The image is absolutely positioned to fill the height and width of the div.media.
  • The loading: lazy attribute delays image loading until it enters the viewport, improving page load speed.
  • The widths attribute specifies available image sizes, including important ones.
  • The sizes attribute sets the image size on the screen to 100vw (view width).

For more information, refer to the documentation of the image_url filter and the image_tag filter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using RestSharp to convert a JSON string into an object

I have been struggling to deserialize the returned response.Content string without success. The WebApi action sends back a modified modelState with extra custom errors. On the MVC side, I attempted several methods but none of them were successful: JsonDe ...

Adding CSS properties to an image within the ImageResourceCell of a CellTable

After creating a CellTable with an image column in GWT using ImageResource, I encountered a problem. I needed to change some CSS properties of the image such as size or adding 'cursor="pointer" for a click event, but was unsure how to do so. When insp ...

Issues with unmarshaling JSON causing values not to display correctly in struct

I've been attempting to fetch a list of reminders from Slack by accessing its API. My goal is to extract the timestamp and user ID from the response. However, I'm facing a challenge in getting the values properly copied into the struct during the ...

Encountering an "unsupported media type" error while using jquery ajax with json in Spring MVC

I am currently working on a Spring MVC application and I am facing an issue in my JSP where I need to pass an object to the controller and then receive the object back in the JSP. Unfortunately, I am encountering an error message saying "Unsupported media ...

Ruby Stateful JSON Parsing Tool

I am currently working with a Ruby server that is continuously reading from a flat file which gets updated every second by another server. This flat file is in JSON format, and I want the server to only read the new data instead of parsing the entire fil ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

Troubles with C variables and memory allocation

My code is experiencing an issue where the variable receiver_buffer seems to be getting data from either json_packet or uu in the function external_auth_format_packet. Below is a snippet from the log: Sep 26 12:35:07 ubuntu sshd[58912]: userauth_external ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

Modify anchor link color in a one-page website by using Jquery to detect scroll position changes when reaching different page sections

Each if statement contains specific numbers to change the text color of the visited/current/active anchor link. The height of the page is dependent on its width. How can this be resolved? Apologies if my explanation is confusing, English isn't my stro ...

Change an object into an XML string without using annotations on the Plain Old Java Object

Can object to XML string conversion be achieved without using annotations on the POJO class? My request is coming as a REST service and it automatically converts to the POJO object. I need to extract the XML string from this object without modifying the ...

Is it possible to make a div jump or bounce if it has a flex display?

I'm looking to add some interactive animation to an image inside a div when my mouse hovers over it. To better explain the issue I'm facing, I created a quick representation of what I want to achieve in the code below. My goal is to have the te ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

Unable to reach deeply nested objects and arrays within an EJS template

Hello everyone, I am attempting to retrieve the response mentioned in the link for my EJS template. At the moment, I have a for-loop that goes through all the campaigns. campaigns.facebook.data[i].insights .data I have tested the following code which se ...

How can I retrieve the value of a div nested within another div?

Alright, let's talk about a situation where we have a draggable HTML div element: <div id="server" draggable="true" ondragstart="return dragStart(event)">Server</div> and also a target div: <div id="target1" ondragenter="return dragE ...

The Talend tRestClient, when configured with a dynamic URL and parameters retrieved from a database, is not

My current challenge involves integrating Talend with a REST web service and passing parameters sourced from a database. I'm working on connecting the PostgresqlInput component with the Rest component, and figuring out how to pass DB row values in th ...

Utilize Angular's ng-repeat directive to iterate through this JSON data structure for implementing user-to

Struggling with the user-to-user messaging interface on an app and having difficulty using ng-repeat on the items. Here is the provided data: { "ID": 4118, "CreatedDate": "2015-08-20T03:12:50.397", "recipient": [ { ...

Ways to center Bootstrap panel in the middle of a webpage

Is there a way to center this entire panel on the web page? I could use some guidance with this. Does anyone have recommendations for a good book to learn Bootstrap design? <div class="panel panel-default" style="max-width:500px;margin-left:auto;margi ...

Save the model with the updated value

Currently, I am working on a piece of code that involves the following: <select ng-model="rule.platforms" ng-options="platform for platform in platforms" name="platform" multiple required> <option value="">-- platform --</option& ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...

CSS | Creating gaps between elements within a form

My form is currently inside a flexbox card with two sides - left and right. The left side displays a picture, while the right side contains the actual input fields. I'm looking to add more space between the different inputs as they feel too cramped at ...