Center a vertically aligned element following a heading, with the content dynamically generated and enclosed in a fixed container

My mind is racing with this problem and I'm not sure if it's solvable, but before throwing in the towel, I thought I'd seek help from the Internet Gods.

Here's a visual representation of what I'm aiming for:

I want the text to align at the top-left corner of the container, while the image should position itself in the center of any remaining space after text wrapping (if applicable).

For a demonstration, check out this demo.

Currently, I am utilizing 'flexbox' and 'margin: 0 auto' to achieve the desired centered layout. However, when working with a lengthy image, using 'position: absolute' on the 'h2' element results in an unfavorable appearance.

Is there a way to employ some flexbox wizardry that takes into consideration the height of the dynamically loaded 'h2' element and centers the image within the available free space?

Here are the constraints to keep in mind:

  • The parent container must maintain dimensions of 200px by 200px.
  • The image cannot be distorted or stretched.

Answer №1

I managed to discover my own resolution by merging @Claudio's concept of a table with some clever use of position absolute.

Take a look at the demonstration showcasing both tall and wide images: DEMO

HTML:

<div class="main-box">
  <table>
    <tr>
        <td class="box-title">
            <h2>
                My title here. :) add some more text
            </h2>
        </td>
    </tr>
    <tr>
        <td class="box-img">
            <img src="//i.imgur.com/NOzWHFF.png" alt="Google">
        </td>
    </tr>
  </table>
</div>
<div class="main-box">
  <table>
    <tr>
        <td class="box-title">
            <h2>
                My title here. :) add some more text
            </h2>
        </td>
    </tr>
    <tr>
        <td class="box-img">
            <img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/Long_March_2D_launching_VRSS-1.jpg" alt="Google">
        </td>
    </tr>
  </table>
</div>

CSS:

*{
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.main-box{
    width: 200px;
    height: 200px;
    border: 2px solid #000;
    background-color: #FFF;
    position: relative;
}
.main-box table{
    width: 100%;
    height: 100%;
    border-spacing:0;
}
.main-box .box-title{
    background-color: rgba(0, 0, 0, 0.1);
    height: 1px;
}
.main-box .box-title h2{
    margin: 0;
    padding: 5px;
    font-family: Helvetica, Arial, sans-serif;
}
.main-box .box-img{
    text-align: center;
    vertical-align: middle;
    padding: 5px;
    position: relative;
}
.main-box .box-img img{
    max-width: 100%;
    max-height: 100%;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

Answer №2

Nothing is impossible, everything is possible! :)

After a lot of effort, thinking, and testing, I finally found a solution to make something work using only HTML and CSS. It may not be the ideal way, but it gets the job done.

The structure is pretty simple. We start with a main div with dimensions set to 200px X 200px. Inside this div, we have a table with two rows - one for the title and the other for a beautiful img.

To style the structure, we remove border-spacing, adjust margins, and apply height: 1px; to the first row of the table (the title row) as a trick.

Why use height: 1px;? By setting the height to 1px, the table row will only take up the necessary height based on its content. This allows the second row (image row) to occupy the remaining space, which can then be centered using vertical-align: middle; and text-align: center;.

If you want to see the code in action, here's a link to the JSFiddle:

https://jsfiddle.net/u61y62r8/

I hope this explanation helps! :)

Answer №3

That should get the job done.

<div class="container">
  <div class="inner">
    <h2>Here Comes a Title</h2>
  </div>

  <div class="inner-2">
    <img src="https://example.com/image.jpg">
  </div> 
</div>

CSS:

.inner { 
    width: 100%;
    height: 50px;
}

.inner-2 {
    height: calc(100% - 50px);
    display: flex;
    justify-content: center;
    align-items: center;
}

.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

Ways to modify color while user moves the screen

I'm working with some jQuery code that changes the colors of elements as the user scrolls down, and I want it to revert back to the original color when scrolling back up. However, the script is not behaving as expected... Here is the original working ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

HTTP request form

I'm currently working on a form that utilizes XMLHttpRequest, and I've encountered an issue: Upon form submission, if the response is 0 (string), the message displayed in the #output section is "Something went wrong..." (which is correct); Howe ...

A mesmerizing Fullscreen CSS Slideshow that creates a stunning double fade in/out effect for overlaid elements on background slide elements

Looking to create a unique slide show using background images and text with specific animations? Check out this jsfiddle. This slideshow features cover background images, displaced text, and button-controlled transitions without auto loop animation. Each ...

Reverse the order of jQuery toggle animations

Looking for something specific: How can I create a button that triggers a script and then, when the script is done, reverses the action (toggles)? (I am currently learning javascript/jquery, so I am a beginner in this field) Here's an example: ...

How can I arrange multiple images within a div to create a circular view?

How can I create a div block with multiple images positioned inside? I'm having trouble applying div CSS properties to the images, and also want them to be displayed in round shapes. ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

Graphic descending within container

Struggling to design some divs for image display, I encountered a problem where the image shifts down by 3 pixels. It seems this is due to a 3 pixel margin on the container div, but I'm puzzled as to why it affects the image position. padding:0; marg ...

Gensim's Word2Vec is throwing an error: ValueError - Section header required before line #0

Hello everyone! I am diving into the world of Gensim Word2Vec and could use some guidance. My current task involves using Word2Vec to create word vectors for raw HTML files. To kick things off, I convert these HTML files into text files. Question Number O ...

What is the best way to vertically align my image for perfect centering?

On one of my pages at , there is a section titled "FREE PICK UP AND RECYCLING OF LARGE QUANTITIES OF ELECTRONICS" with a picture of a truck. The image is perfectly centered vertically between the pictures on its left and right. Another page I have at fea ...

How can I show the content of a variable in Next.js without displaying any HTML tags?

For instance, I have the description variable set up like this in NextJS: description={storeDetail?.translation?.description} When outputting the description, it shows me <p>Tenis</p>. However, I would prefer to display just "Tenis" without th ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Ways to display dynamic content within a div using Bootstrap's vertical tab through a click event in PHP

I have been working on displaying static content in a div using Bootstrap vertical tabs, similar to this: Link: However, I am facing an issue with showing dynamic content in a div using a Bootstrap vertical tab through a PHP click event. I have been try ...

What is the method for identifying the selected radio button that has been dynamically generated after clicking the submit button?

Despite this question being asked multiple times before, I am struggling to find a solution that fits my specific scenario. Initially, I have a static radio button that I create. The HTML code is as follows: <body> &l ...

Is there a way to control the quantity of items being displayed in my ng-repeat directive?

Here are the objects in my array: 01-543BY: Array[1] 03-45BD23: Array[1] 03-67BS50: Array[1] 06-78FR90: Array[1] 07-467BY3: Array[1] 09-23DF76: Array[1] Currently, I have a total of six objects, but I only want to display four. This is how I am using ng- ...

embed a hyperlink onto a live video at a designated moment within an HTML document

Can anyone help me figure out how to overlay a link over a video playing at a specific time on an HTML page? I know it's easy to do on Youtube, but I need to accomplish this task without using Youtube. :) Thank you in advance for any assistance! ...

Creating a split hero section view using a combination of absolute/relative CSS techniques, Tailwind, and React

I'm in the process of creating a website using Nextjs, React, and TailwindCSS, and I aim to design a Hero section that resembles the one on the following website. https://i.sstatic.net/tq3zW.png My goal is to: Have a text title and buttons on the l ...

Using CSS to Showcase the Art Gallery Page

This is my unique gallery display: https://i.stack.imgur.com/RddD8.png Here is the look I am going for https://i.stack.imgur.com/kuOye.png I want to showcase images in a slightly messy yet awesome way However, I encounter an issue when some images have ...

Incorporate Vimeo video with full-width display

When embedding a Vimeo video on my website, I use the following code: <div class="fys-fp-content-wrapper"> <div id="fys-fp-video"> </div> </div> #fys-fp-video { position: relative; padding-bottom: 56.25%; padding-top: ...

CSS causing black bars to appear when image is moved

I recently started working with HTML/CSS and JS, but I've encountered a small issue. I'm using the bootstrap carousel and it's functioning well, but when I try to move the image higher up, black bars appear at the bottom as if my images are ...