Steps to make a div that perfectly matches the size of the image inside, ensuring responsiveness

Currently, I am in the process of creating a mobile e-mail template without the use of JavaScript. The main requirement is for the template to be responsive.

My goal is to insert multiple images in a row, with the ability for the images to scale down when the screen size decreases. To achieve this, I utilized CSS tables and table-cell properties to allow the images to resize accordingly.

However, due to the high chances of images being blocked by e-mail clients, I have been asked to incorporate a gray placeholder. This placeholder should display the "alt text" of the image when it fails to load, while maintaining the same size and responsiveness as the actual image.

Progress on this task can be seen in the following fiddle: http://jsfiddle.net/ow7c5uLh/29/

To address these issues, I have structured the HTML as follows:

<div class="table">
    <div class="table-cell">
        <div class="placeholder">
            <img src="http://lorempixum.com/120/60/" alt="alt text" width="120" height="60" />
        </div>
    </div>
    <div class="table-cell">
        <div class="placeholder">
            <img src="http://lorempixum.com/120/60/" alt="alt text" width="120" height="60" />
        </div>
    </div>
    <div class="table-cell">
        <div class="placeholder">
            <img src="http://lorempixum.com/120/60/" alt="alt text" width="120" height="60" />
        </div>
    </div>
</div>

In terms of CSS styling:

.table {
    display: table;
    table-layout: fixed;
    width: 100%;
}

.table-cell {
    display: table-cell;
    text-align: center;
    padding: 0 5px;
    border: 1px dotted black;
}

.placeholder {
    max-width: 120px;
    max-height: 60px;
    margin: auto;
    background-color: #505050;
    color: #FFFFFF;
}

img {
    max-width: 100%;
    height: auto;
}

However, I am encountering two main issues:

  1. As the screen width decreases and the images scale down, the background-color of the placeholder becomes visible around the image edges. This is due to the placeholder-div scaling similarly to the image, but its height appears to be slightly larger than the image height. I am unsure of the reason for this discrepancy.
  2. When the images fail to load (such as making the image URL invalid in the fiddle), the placeholder-div's height collapses. How can I ensure that the placeholder maintains its correct height even in such cases?

For future reference, the actual images used in the template may vary in size, but I will have access to their dimensions and aspect ratio. I plan to include these values directly in the HTML code rather than in a separate CSS file.

Any assistance or guidance on resolving these issues would be greatly appreciated. Thank you!

Answer №1

To convert your CSS img rule to a block element instead of inline, simply add display: block and everything will be set: Check out the Fiddle

In the fiddle, try changing one of the src="...." to src="" and notice how the cell scales automatically.

To scale the alt="text" in your HTML, include the rule

img[alt] { font-size: 2vw; overflow: hidden }
in your CSS. The overflow: hidden will trim excess text when the alt is larger than 120x60px.

(Note: [alt] is referred to as an 'attribute' in CSS. Search for 'css custom attribute' if you want to master creating your own.)

View the updated Fiddle here

I recommend keeping the width and height rules of the placeholder, but you could adjust them to min-height/min-width to indicate that something is missing. Alternatively, you can use max-width: 100% and eliminate max-height, depending on your specific needs. Just make sure to define image size limitations somewhere down the line (e.g., setting a width for the table in pixels and a (max-)width for its children in percentage).

Answer №2

Eliminate:

img {
   height: auto;
}    
issue-1 & 2: 

    img {
       max-width: 100%;
       max-height: 100%;
    }

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

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

Centering text on input placeholder

What is the best way to center a placeholder vertically in an input field? input[type='text']{ background-color: rgba(255,255,255,.4); border:3px solid rgba(0,0,0,.5); min-height: 45px; border-radius: 6px; color:#fff; } input[type=&apo ...

Looking for a way to make one image disappear briefly while transitioning to another image in Javascript

**Hey there, coding enthusiasts! I could really use some help right now. I am trying to create a smooth image transition effect using Javascript, where one image fades out while the next one fades in seamlessly. As someone who is still relatively new to pr ...

There was an issue in the v-on handler that resulted in an error: "TypeError: The property '$createElement' cannot be read because it is undefined."

I am encountering an issue with some basic input/output code. The task at hand is to receive input in Newick format and use it to create a tree. However, I am struggling to even receive the input correctly. Below is the HTML code snippet I am using: ...

Align a component vertically in a FlexBox using Material UI

I have a React app where I created a card with specified min width and height, containing only a header. I want to add flexbox that occupies the entire left space with justify-content="center" and align-items="center". This way, when I insert a circular pr ...

Looking to retrieve the values of a 3-level dropdown using ajax. Successfully fetched the value of the 1st dropdown, but unsure of how to retrieve the values of the 2nd and

I have successfully managed to retrieve all values, but when the 2nd and 3rd drop-downs are populated through Ajax, how can I access those values? I am looking for a way to fetch the values of the 2nd and 3rd drop-down without resorting to session variable ...

Tips for styling row headers in Vaadin with CSS

I am in need of assistance with a problem I am facing. Recently, I started learning the Vaadin framework and I am trying to apply CSS to the row headers (first cell of each row), but so far I have not had any success. Below is the code that I have been usi ...

having difficulty choosing a single radio button at once

I'm having trouble selecting just one radio button at a time. Instead, multiple buttons are being selected. I'm new to HTML and this is the code I'm using. Can someone please assist me with this issue? <form name="ans_a" onsubmit="return ...

Increase the gap between vertically aligned columns in Bootstrap 4 by adding spacing

Managing vertical spacing between columns that switch from horizontal to vertical at breakpoints can be challenging. While there are solutions available when dealing with forms, applying them to multiple columns wrapping in a row can be tricky. I have atte ...

Applying "Max-Height" property to the cells of a kendo

I've been struggling to figure out how to set a max-height for a tr or td element within a Kendo grid. Is it possible to set the height to 100% and restrict the max-height to 200px? The grid itself is scrollable with a height of 500px, so the scrollin ...

Arranging divs in a stack and implementing a toggle function for displaying and hiding them

I am currently enrolled in a web development course and am eager to explore beyond the limitations of the class. I successfully created a jQuery slide show in one div, and now I want to showcase additional features in two other divs, stack them together in ...

Prevent the Spread of an Event for a Particular Controller

tl;dr Summary Develop a function that is able to handle a specific event on multiple elements within a hierarchy. The function should execute when the event is triggered on the first element reached during bubbling, but should not continue executing or re ...

Converting table data to JSON using JavaScript, including rows for "parent" and "children."

To create a JSON object by selecting values from multiple rows of a table using checkboxes, follow the structure below. The parent row, identified by the class 'primary color,' will be included in the JSON, along with the selected child rows. The ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Is there a way to insert an attribute in HTML without simply appending it to the end of the tag?

I've been working on incorporating the code snippet below that I found in an angularjs table sort function. In the code, you can see the ts attributes being added to the html. However, this method is not suitable for hosting on Salesforce. Can anyone ...

The Send.php script is missing the input fields for Name and Email

Running my own website at CrystalVision.com, I have some challenges with my PHP skills. The issue lies within my send.php file. Although the email functionality works fine and I receive messages, the Name and Email fields filled in by users are not display ...

What could be causing this JavaScript code to use 50% of the CPU and consume a significant amount of memory in the

I'm experiencing an issue with my banner rotator code. Here is the code snippet: function ban_rot() { //First preload images // counter var i = 0; // create object imageObj = new Image(); // set image list images = new A ...

Prevent the display of hyperlinks in the status bar when hovering over a hyperlink or button

The application I'm working on has a default status bar at the bottom of each screen that displays URLs linked to buttons and icons. For example: https://i.stack.imgur.com/ZFTsp.jpg I am trying to prevent the display of URLs associated with hyperlin ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

Align the text in the center of the image, which is depicted as a bullet point

I am currently using images as bullet points for my Github Pages (markdown files), following the instructions outlined here. My goal now is to vertically center the text next to the image. This is demonstrated here (cf. lower third of page), however, I am ...