Ensure that each row of x images has the same height based on the height of the viewport

Currently, I am working on a website using HTML and CSS, specifically focusing on a "blog" header section. I am aiming to create a responsive grid layout featuring x images with equal heights (width adjusted according to their natural dimensions) and consistent padding, arranged in y rows based on the viewport width. My initial approach involved placing all images in a single row before considering splitting them into multiple rows. My main query revolves around determining how to assign a uniform height (and corresponding widths) to all images in the row based on the viewport height. The height should be specified in pixels as a fixed percentage relative to the viewport height, keeping in mind different minimum-width scenarios (480px, 768px, 1140px).

This is the solution I have devised:

HTML

<ul class="blogGrid">
    <li>
        <img class="blogPost" src="//dummyimage.com/400x300/000/fff&text=hello+world" />
    </li>
    <li>
        <img class="blogPost" src="//dummyimage.com/100x100/000/fff&text=hello+world" />
    </li>
...
</ul>

script.js

/** A utility function to calculate the common image height in pixels based on a fixed  
 * percentage of the viewport height per media screen
 */
var imageHeight = function getImageHeight(h) {
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    if (h >= 1140) {
        imageHeight = 0.26 * h;
    } else if (h >= 768) {
        imageHeight = 0.32 * h;
    } else (h >= 480) {
        imageHeight = 0.34 * h;
    }

    return imageHeight;
};

/** A utility function to calculate the local image widths in pixels based on each image's natural  
 * dimensions
 */
var imageWidth = function getImageWidth(imageHeight, naturalWidth, naturalHeight) {
    return (naturalWidth / naturalHeight) * imageHeight;
};

/** Assigns height and width to each image
 */
var blogPostImg = document.getElementsByClassName('blogPost');

if (blogPostImg && blogPostImg.style) {
    blogPostImg.style.height = imageHeight;
    blogPostImg.style.width = imageWidth;
}

css

body {
    margin: 0;
}
ul.blogGrid {
    list-style: none;
    padding: 0;
    margin: 0;
    display: table;
    border-collapse: collapse;
}
.blogGrid li {
    display: table-cell;
}
.blogGrid li img {
    display: block;
    height: 300px;
    padding: 5px;
}

Unfortunately, my current implementation is not functioning as expected, leaving me in a state of uncertainty. While I have been exploring JavaScript solutions, my lack of experience in this area is evident. I am reaching out for guidance, feedback, code examples, or any form of support from the community. I am eager to learn and improve, and any input is greatly valued. Thank you in advance for your assistance!

ANY COMMENTS ON MY CODE, TIPS, CODE SNIPPETS, INTEREST, ANYTHING..! IS HIGHLY APPRECIATED. THANK YOU

Answer №1

Have you experimented with utilizing jQuery to modify your DOM attributes?

You might consider assigning classes to your images and selecting them using a jQuery selector: $('.class-name'). Then, you can loop through the returned collection to adjust the attributes of each image. This could be where you are encountering an issue:

var blogPostImg = document.getElementsByClassName('blogPost');

This line will actually assign blogPostImg to an array of elements. You will need to implement something like a forEach loop to iterate through them and adjust the properties of each image.

Alternatively, you could group all the images in div rows, set the height based on vh, and apply overflow: hidden; to crop the content. Keep in mind this method won't scale the image, just trim it.

Providing a jsfiddle link would greatly help in pinpointing the exact issue with the code you have written.

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

A guide to eliminating missing tags from HTML code using Asp.net

There have been instances where the HTML code we receive from certain websites does not have proper tag endings, causing issues with our UI. For example: <br /><p>hello the para start here </p> <p>some text and no ending tag As yo ...

Error message appearing when attempting to add a product to the cart in Magento using AJAX

Encountering an error with the magento 1.8 ajax cart, stating "product not found" The javascript code I implemented: function setLocationAjax(url,id){ var data = jQuery('#product_addtocart_form').serialize(); data += '& ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

Tips for creating CSS3 animations in Angular triggered by mouse clicks

I'm working with a span that utilizes a Bootstrap icon. My goal is to fade out and fade in the same element (span) on click, while toggling the class (icon). There's a boolean variable called showLegend which determines whether or not to animate ...

Troubleshooting problem with image overlay alignment in Bootstrap 4 Card

I am currently utilizing Bootstrap 4 and am attempting to create a card-based layout for showcasing my stores. Within this design, I have a location marker that should appear over the store image with a 5-star rating positioned on the same line, floating t ...

Enhanced Compatibility of HTML5/CSS3 Modal Box with Internet Explorer

I'm experimenting with HTML5/CSS3 for the first time and have implemented a cool little link to display a dialog (modal) on one of my web pages. While this works perfectly in Chrome/Firefox, it unfortunately doesn't function properly in Internet ...

What is the best way to pass an array to a child component in React?

I am having an issue where only the first element of inputArrival and inputBurst is being sent to the child component Barchart.js, instead of all elements. My goal is for the data to be instantly reflected as it is entered into Entrytable.js. EntryTable.js ...

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Reignite the dynamically configured fancybox

Encountering an issue with reopening a dynamically created fancybox. The process involves initiating an AJAX request to retrieve image information, preloading the images using jQuery, and then creating a fancybox instance upon successful preload. After cl ...

It encounters an error when attempting to fetch the 'src' attribute of a class

Is there a way to extract the HTML link found in the src attribute within a specific div on a webpage? The div structure is as follows: <iframe width="100%" class="idemo2" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="some/privat ...

Angular error TS2322 arises when attempting to assign a type of 'Observable<{}>' with the share() operator

Currently diving into Angular 5, I've been exploring the Observable/Observer pattern to facilitate event sharing and data changes among subscribers. Below is a snippet of the code in question: ... @Injectable() export class NidoService { ... eve ...

Access the child scope's attribute within the parent scope in AngularJS

angular.module('myApp',[]) .controller('Parent',['$scope',function($scope){ //no specific definition }]).controller('Child',['$scope',function($scope){ $scope.user={name:''}; //create a us ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Creating a responsive design using Bootstrap4

Today, I made the switch to bootstrap4 and enabled flexbox in _variables.scss. However, I'm still confused about the flexbox capabilities of bootstrap4. Some questions I have include: How can I utilize flex-direction:column? Is it possible to creat ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

In Mobile View, I want to swap out my current image for text to keep it hidden

I am attempting to include text that is only visible in Mobile View as a replacement for my logo. Below is the code I am using: CSS: @media only screen and (max-width:1024px) { header .logo { display: none; } header .logo a { display: non ...