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

The margins are misaligned on a tablet-sized device due to an issue with the media

Why are the margins not maintained well when media queries are applied for tablet view, i.e., medium-sized devices? The third block is coded to acquire 100% width in medium size but the margins do not align well. What could be causing the third paragraph t ...

Link functioning properly for one item but failing for another

I am facing an issue with my index.html file that contains the following code: <li> <a href="imprint.html#imprint-link"> <div class="main-menu-title">IMPRINT</div> </a> </li> Clicking on the "IMPRINT" link loa ...

Blur effect on backdrop-filter causing shadowy inset borders (specific to Chrome and Windows)

Note: The issue mentioned below has been resolved in the latest version of Chrome (119.0.6045.200). While transitioning on backdrop-filter, I have observed a dark inset shadow that is only visible during the transition. This behavior seems to occur only ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Tips for positioning a 404 message at the center of a webpage

Struggling with centering a 404 error message on your Bootstrap 5 page without messing up the footer layout? When the viewport is small, the 404 message may end up getting covered by the footer. Feel free to check out the code snippet in full view to see ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

Is the height of the element determined by the parent rather than the content?

I need help with a layout featuring three containers - Total (with a red border), Left (yellow border containing an image), and Right (blue border containing text). Left is set to approximately 30% width with float: left, while Right is set to 70% width w ...

Effortlessly browse through directory with the seamless integration of AngularJS or

Hey there! I'm working on a really cool feature - creating a list with editable inputs. However, I've encountered a bit of an issue. Is there any way to navigate through this list using arrow keys and focus on the desired input? .content ul { ...

What is the best way to incorporate animation using Tailwind CSS within my Next.js project?

I have a challenge with placing three images in a circular path one after the other using Tailwind CSS for styling. I've identified the circular path and keyframe style for the images. How do I configure this style in my Tailwind config file and imple ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

Boost website performance with Google Page Speed by optimizing CSS above the fold using this innovative Bootstrap Template Plugin

My Google PageSpeed Insights report suggests that I should place my CSS below the fold. However, Bootstrap is being used as my templating plugin. I am contemplating printing bootstrap.min.css inline on my homepage, but I hesitate because it may lead to i ...

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

Display issue with ul and li elements in Safari browser causing menu to appear incorrectly

Although I am new to CSS, I managed to create a menu on my website that hovers over the background video successfully. It is a basic menu using a ul with li elements and it appears as intended in all browsers except Safari. In Safari, the menu items stack ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...

Changing the border color of a Material UI textbox is overriding the default style

Upon the initial page load, I expected the border color of the text box to be red. However, it appeared grey instead. I tried setting the border color to red for all classes but the issue persisted. Even after making changes, the border color remained unch ...

Issues with CSS3 Animation failing to trigger upon hovering over links

Background: Looking to design a visually appealing hover effect for links in the future Current Demo Link: You can view the demo here specifically on Firefox Browser. body { color:#ffffff; font-family:"Helvetica"; font-size:12pt; backgr ...

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...

The list countdown for loop only appears in the initial iteration

Hey there, I'm currently facing an issue with duplicating my JavaScript countdowns and displaying images of cards on each loop iteration. Strangely, the countdown only appears in the first instance even though it's within the loop. I'm seeki ...

Script to pop up cancel alert box

There's a dilemma with this code - if you click CANCEL the first time the box pops up, it continues to run. I'm unsure of how to make it redirect to the underlying page when clicked on cancel for the first time. var numero= prompt ("Enter a nu ...