Is it feasible to include an image caption using CSS pseudo elements?

I am searching for the most efficient and manageable approach to accomplish this task:

These are text slugs that will be attached to various images across the site. Although the messages remain consistent, the images differ and are sourced from a CMS.

I am familiar with one method involving relative positioning of the image and an absolutely positioned child div containing the desired text.

However, given that this technique involves adding HTML code to each image, I am exploring alternative options such as utilizing a CSS class with the :before pseudo-element. Unfortunately, applying the class to a wrapping link does not produce the desired outcome:

<a href="#" class="tabw"><img src="imagepath" alt=""></a>

.tabw img:before {
content: 'there's a better way';
color: red;
font-size: 18px;
}

Is it feasible to achieve this using only CSS? By having the CMS apply the class attribute when necessary, the process would become more streamlined.

Answer №1

Indeed, ::before and ::after do not have an effect on images directly. However, you can utilize them on the surrounding anchor element:

a{
  position: relative;
}

a, a > img{
  display:inline-block;
}

a::before{
  content: 'there is another approach';
  position: absolute;    
  left: 0;
  top: 0;     
  width: 80%;
  height: 20px;
  left: 10%;  
  background: #000;
  opacity: 0.4;      
  color: red;
  font-size: 18px;
}

example

If you prefer to embed the text within the HTML, you'll need to introduce a real element with it in your hyperlink (and apply identical styling, excluding the content property)

Answer №2

This is my approach using jQuery :

HTML

<div class="photo">
    <img src="http://www.example.com/photo.jpg" alt="image"/>
    <div class="description">Description here</div>
</div>

CSS

.photo {
    position:relative;
    width:300px;
    height:300px;
}

.photo img {
    max-width:100%;
}

.photo .description {
    display:none;
    position:absolute;
    top:0;
    height:30px;
    line-height:30px;
    width:100%;
    text-align:center;
    background:rgba(0,0,0,0.7);
}

jQuery

$('.photo').hover(function() {
    $(this).find('.description').fadeIn();
}, function() {
    $(this).find('.description').fadeOut();
});

Check out the demo

Answer №3

IMPORTANT MESSAGE FOR THOSE WHO STUMBLE UPON THIS DISCUSSION: Please be aware that in Firefox 21 and IE 9/10, there may be issues with oversized images not displaying correctly. Despite setting max-width to 100%, the images were still forced to 100% width.

I found a solution based on the chosen answer above however, I needed to change the A tag to display:block instead of display:inline-block to resolve the issue.

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

What is the best way to position an element above another specifically for mobile viewing?

Currently, I am working with Bootstrap 3.x and have two divs assigned as col-lg-6. These divs are referred to as Column X and Column Y. In the desktop view, Column X is positioned on the left side while Column Y resides on the right side. My query pertai ...

I positioned my popups at bottom:0, but strangely enough, they start moving up after being hovered over 2-3 times

Check out my blog where I'm having some trouble with popups. They start at the bottom but keep moving up each time they are hovered over more than once. Any suggestions on how to fix this issue? Edit: After some experimenting, it turns out that the " ...

Displaying a single div while concealing the remaining two divs upon pressing a button

There are 3 hidden DIVs on a webpage. Clicking on a heading should display one DIV while hiding the other 2. Below is the code I used to achieve this, but it doesn't work properly on all browsers like iPad and iPhone. Is there a more efficient way to ...

What is the best way to change the CSS style of a class using jQuery?

Struggling to make changes to a specific class style without success. I am aware of the addClass function in jQuery for adding a class, but not sure how to override just the style of a class. Is there a method to override styles directly? ...

Enhance the current bootstrap sidebar by making it collapsible

My project is built in bootstrap and features a top navigation bar along with a sidebar. I would like to make the sidebar collapsible, similar to this example: The only challenge is that the sidebar in my project is positioned on the left side of the pag ...

"The server responded with a 405 error message indicating that the requested method

I have been working on a registration form project using HTML, JS, NodeJS, and SQLite. However, I am encountering an issue with the fetch function when trying to post the inputted information into the database. I keep receiving a POST 405 (Method Not Allo ...

Pause jQuery at the conclusion and head back to the beginning

As a beginner in the world of jQuery, I am eager to create a slider for my website. My goal is to design a slideshow that can loop infinitely with simplicity. Should I manually count the number of <li> elements or images, calculate their width, and ...

Review a roster of websites every half a minute (Revise pages every half an hour??)

Just starting out with HTML coding! Can someone please provide the code that will allow me to save various webpages and automatically cycle through them every 30 seconds? And also ensure that the webpages are updated every 30 minutes. ...

What is the best way to enclose a block of content with <div> and </div> tags using the append() function?

My goal is to add an outer div container by first appending it, then adding content, and finally appending the closing tag. However, I'm encountering an issue where the div I added at the beginning automatically closes itself, resulting in two separat ...

Horizontal scroll through Bootstrap 4 navigation tabs

I'm currently using the newest Bootstrap 4 nav-tabs feature to create tabs and I'm aiming to keep all the tabs in a single horizontal line that can be scrolled. I've attempted to use various JavaScript plugins, but none of them seem to func ...

Most bizarre glitch in IE9 found (disable internet, watch page display go haywire)

My local webserver (apache) on my laptop is successfully serving up a content management system that looks fine in both IE9 and Firefox. However, when attempting to demo it without an internet connection, the elements were misaligned and looked terrible i ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

Tips for adjusting Default ASP page size in Visual Studio for big screens?

My ASP page is not fitting the entire screen on large screens. How do I make it responsive? The CSS file contains the following styling: /* DEFAULTS ----------------------------------------------------------*/ body { background: #b6b7bc; ...

Inject pure HTML code into a react div

I have extracted raw HTML content stored in the database and I am attempting to display it within a div element. const style = { border: '2px solid #eee', height: '270px', width: '100%', overflow: 'auto&ap ...

What could be causing this addEventListener to fail when I am assigning elements to a class?

I've encountered an issue with my code where I have two text inputs and two date inputs. I tried to select all of them using QuerySelectorAll with a class, added a click listener that should change the textContent of a div element to "", but it's ...

Is it possible to display the footer only when I scroll to the very bottom of the page using ScrollMagic?

After browsing through numerous questions on StackOverflow similar to this one, I attempted various solutions but unfortunately, nothing seemed to work for me. :( Greetings! My current setup involves utilizing a MVC model in PHP. I'm incorporating ...

Is there a CSS selector that allows me to exclude the final two child elements?

Is there a way to apply bottom-border to certain div elements within their parent, excluding the last two? It's important to note that the number of child elements can vary: <div id="parent"> <div> One </div> <div> Tw ...

One-page website with dynamic JavaScript features

Recently, I inherited a project for a client who already has a fully developed website. This website functions similar to a social media platform like Twitter, where users can create accounts, post 'tweets', and gain followers. Upon examining t ...

Trigger jQuery event on a table cell

I am looking to select the td element using jQuery <table width="60" height="60" cellpadding="0" cellspacing="0" border="0" style="float: left; margin: 1px" background="images/data/source_red.gif"> <tbody> <tr> <td ...

Show the picture stored in the S3 cloud storage

I'm facing an issue with displaying images uploaded to S3. I've checked the permissions and can access the URL successfully to retrieve data. However, when I insert the URL into an image tag, it shows up as a broken link. Upon inspecting the net ...