How to align text with an image as the size of the image adjusts

I'm brainstorming creative ways to handle a webpage section where the image will be swapped out with various images (with widths up to 620px) and a text caption is positioned over it. I aim for the text to adjust its absolute position based on the width of the image, not the width of the relatively positioned container.

One idea that crossed my mind is using background-image instead of an actual image, but then I'd have to address the issue of having an empty div with a background image, requiring a hardcoded height - which won't accommodate varying image heights.

If anyone has any solutions or suggestions, I'd appreciate hearing them. Thank you!

Answer №1

It's a bit unclear if I completely understand, but here is my take on how to achieve what I believe you are attempting.

Start by creating a container with position relative, defining widths and heights, and setting overflow to hidden:

.outer-container {
  position: relative;
  width: 250px;
  height: 250px;
  overflow: hidden;
}

Then, insert an inner container within it that has position set to absolute:

.inner-container {
  position: absolute;
}

To finish, style your overlay text to fill the entire width and horizontally center it (or position it as desired):

.overlay-text {
  position: absolute;
  text-align: center;
  width: 100%;
  margin: 0;
}

Check out this example on jsfiddle for reference: http://jsfiddle.net/ZNvaf/1/

Best of luck!

Answer №2

Adding more CSS to enhance the look of the previous answer:

<div class="pictureframe">
    <div class="description">Bob Dylan</div>
    <img src="http://greenobles.com/data_images/bob-dylan/bob-dylan-01.jpg">
</div>​
.pictureframe{
    position: relative;
    float: right;
}
.description{
    position: absolute;
    top: 0;
    left: 0;
    font-family: Arial, sans-serif;
    font-size: 1em;
    background: rgba(255,255,255,0.7);
    color: #000;
    padding: 0.5em 1em;
}

​Check out the jsFiddle example for more details.

Answer №3

By setting the div containing the image to inline-block, its width will adjust based on the size of the image it holds.

Once you have the container properly sized, you can easily center other elements inside it, such as captions, by using a wrapper with text-align: center. Alternatively, you can achieve the same effect without a wrapper by setting the left and right margins to auto.

Check out this example for a demonstration: http://jsbin.com/uyajaw/3/edit (with visible borders and backgrounds for clarity).

Try resizing the image and notice how the caption remains centered.

Keep in mind that if your caption is larger than the image, it might cause the container to expand and disrupt the center alignment. To prevent this, consider using

position: absolute; left: 0; right: 0;
on the caption or giving it a fixed width smaller than the image.

Answer №4

Is it possible that I am overthinking this situation? However, here is a solution to consider. If your goal is to avoid aligning the caption with the wrapper div, you may want to handle the imagesLoaded event using the jQuery plugin. Otherwise, without accounting for this event, you might end up with an image width of 0 when not loaded or retain the previous image width (unless you revisit it).

Check out this example on Fiddle, showcasing a fixed-width wrapper div and a centered caption.

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

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

Contrast between JQuery .display/.conceal and CSS view:invisible

I'm working on a way to toggle the visibility of a Div element using JQuery: $("#Progress").hide("fast"); But I want the #Progress div to be hidden by default. <div style="height:30px;margin-top:5px"> <div id="Progress" style="visibil ...

Strangely glitchy navigation bar using jQuery

Over at this website, there's a top navbar that shrinks using jQuery when scrollTop exceeds 100px. The functionality works as intended, but there's an annoying stutter issue where the navbar starts jumping up and down erratically after slight scr ...

Displaying received image using Express JS

Currently, I am working on managing two separate Express JS applications. One of them serves as an API, while the other application interacts with this API by sending requests and presenting the received data to users. Within the API route, I am respondin ...

Organize the HTML table upon importing

In my code, I am populating a table with data retrieved from a JSON object. Here is the JavaScript snippet: if (jsonObj[0].array !== 'undefined' && jsonObj[0].array.length > 0) { for (var i = 0; i < jsonObj[0].array.length; i++ ...

iOS is not receiving JSON data in the response headers

I am currently utilizing the CocoaHTTPServer for establishing my server connection. However, I encountered an issue with retrieving JSON data in the header file of my HTML page (web client). Here is the code snippet : HTML Page : endAPSession: funct ...

Displaying the number zero in TYPO3 Fluid without it being empty or NULL

Within my TYPO3 Fluid template, I am encountering an issue where I need to display a value only if it is not empty. Currently, my approach is as follows: <f:if condition="{myvalue}"> <div class="myclass">{myvalue}</div> </f:if> Th ...

JavaScript: Locate the HTML Attribute that Matches an ID

If you want to use just JavaScript, without relying on libraries like JQuery, how can you retrieve the data attribute associated with a specific Id? For example: <div id="id-test" data-qa="data-qa-test"> </div> Input: &quo ...

What is the best way to prevent scrolling in one column while allowing another column to scroll normally?

On my website, I have two divs positioned side by side. I am looking to keep one div fixed without scrolling while allowing the second div to scroll normally. How can I achieve this? For a clearer visual, refer to this image: Sample Image ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

Why are the items I have inserted inside my <div> tag not appearing on the screen?

What could be simpler than this: {this.state.dash ? <div className='dashWrapper slide'> HELLO </div> : null} I've tried everything, but nothing seems to show up inside the div. ...

Tips for expanding a script that relocates a logo into a navigation consisting of several unordered lists

I recently implemented a jQuery script to center a logo within my main navigation bar only when the screen width is above 980 pixels. It was working perfectly fine with a single unordered list, but as soon as I added more unordered lists within the nav, it ...

In JavaScript, you can ensure that only either :after or :before is executed, but not both

My html slider is causing me some trouble <div class="range-handle" style="left: 188.276px;">100,000</div> Upon loading the page, I noticed that in Firebug it appears like this https://i.sstatic.net/Rgqvo.png On the actual page, it looks li ...

Showcase an image stored in my sqlite3 database on my Python Flask web application

My goal is to create a web application connected to a database where users can search for specific names and display the corresponding image stored in the database. The images in the database are stored as png BLOBs. The database is structured with a tabl ...

The problematic max-width with srcset attribute

Here's the HTML markup I'm working with: <picture> <source srcset="img/home-page/placeholders/placeholder_2560.jpg" media="(max-width: 2560px)"> <source srcset="img/home-page/placeholders/placeh ...

Utilize HTML search input to invoke a JavaScript function

I am currently facing an issue with a navbar form that I have created. The goal is to allow users to input either a 3 digit number or a 5 digit number, which should then trigger a function to open a specific link based on the input. However, I am strugglin ...

mentioning a JSON key that includes a period

How can I reference a specific field from the JSON data in Angular? { "elements": [ { "LCSSEASON.IDA2A2": "351453", "LCSSEASON.BRANCHIDITERATIONINFO": "335697" }, { "LCSSEASON.IDA2A2": "353995", "LCSSEASON.BRANCHIDITER ...

Updating part of a page while also changing the navigation

Apologies in advance, as this is my first attempt at coding a website. I have a specific need where I want to update only one div on my web page when a link in the navigation bar is clicked. <body> <div id="wrapper"> <header id= ...

Tips for adding base64 image in codeigniter

Currently I am working on a project using PHP. The API sends me images in Base64 format and my task is to save/store them in the database and upload them to the server. However, I am facing an issue with the code I have written as it throws the following ...

Update D3 data, calculate the quantity of rows in an HTML table, and add animations to SVGs in the final

Attempting to update data in an HTML table using D3 has proven to be quite challenging for me. My task involves changing the data in multiple columns, adjusting the number of rows, and animating SVG elements in each row based on new data arrays. Despite tr ...