What is the method for overlaying an image and having it expand to fit the parent container using flexbox?

I'm working on styling an HTML element where I want the txt-box div to be centered within its container, overlaying an image while expanding to fill the container. The goal is for it to have a margin of equal width on all sides, creating a border-like effect around the image.

The current HTML structure achieves part of what I need, but I've noticed that the vertical and horizontal margins are slightly off when the browser window is resized.

I suspect that my use of flex-grow may not be entirely accurate. While I know that setting a grow value allows the txt-box to expand as intended since it's the only element with that property, there seems to be issues with achieving consistent margins. Once I figure this out, adding a margin to txt-box should do the trick.

I seem to be missing something crucial about how flex-grow operates. Can you help clarify my understanding?

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  border: solid 2px red;
  position: relative;
}

.container img {
  width: 100%;
  flex-grow: 0;
  flex-shrink: 0;
}

.txt-box {
  background-color: white;
  display: flex;
  padding: 5px;
  border: solid 2px blue;
  flex-grow: 1;
  position: absolute;
  width: 90%;
  height: 80%;
}
<div class="container">
  <img src="blocks.png" />
  <div class="txt-box">
    hello world
  </div>
</div>

Answer №1

Special thanks to Michael Benjamin for guiding me towards enlightenment. After some trial and error, I finally cracked the code. It turns out that my initial question was just a piece of the puzzle I needed to solve. The key is using background-image:url('...') and ensuring that both the table and row elements are set to display:flex.

JSFiddle Link

<html>
<head>
    <style>

        .flex-table {
            flex-flow:column;
        }

        .flex-row {
            flex-flow:row;
        }

        .container {
            align-items: center;
            justify-content: center;
            padding: 20px;
            border: solid 2px red;
            background-image:url('https://i.imgur.com/Ck7BXBo.jpg');
            background-size:cover;
            background-repeat:no-repeat;
            max-width:500px;
        }

        .txt-box {
            justify-self:stretch;
            align-self:stretch;
            border: solid 2px blue;
            background-color: rgba(192,192,192,0.5);
        }


        body, .flex-table, .flex-row, .container, .txt-box  {
            display:flex;
            flex-grow:1;
        }

        @media (max-width: 768px) {
            .flex-row {
                flex-flow:column;
            }
        }

    </style>

</head>
<body>

<div class="flex-table">
    <div class="flex-row">
        <div class="container">
            <div class="txt-box">
                hello universe 1
            </div>
        </div>

        <div class="container">
            <div class="txt-box">
                hello universe 2
            </div>
        </div>

        <div class="container">
            <div class="txt-box">
                hello universe 3
            </div>
        </div>
    </div>


    <div class="flex-row">
        <div class="container">
            <div class="txt-box">
                hello universe 4
            </div>
        </div>

        <div class="container">
            <div class="txt-box">
                hello universe 5
            </div>
        </div>

        <div class="container">
            <div class="txt-box">
                hello universe 6
            </div>
        </div>
    </div>
</div>
</body>

</html>

Answer №2

Why is my understanding of flex-grow not working as expected?

The issue arises when trying to apply flex properties to absolutely positioned children within a flex container.

§ 4.1. Absolutely-Positioned Flex Children

Due to being out-of-flow, absolutely positioned child elements of a flex container do not conform to the flex layout rules specified.

Consequently, using flex-grow: 1 on the txt-box element does not produce the desired effect and is essentially ineffective.

To address this issue and achieve the intended layout where the image acts as a background and the text box follows specific design requirements, it is recommended to position the image absolutely while maintaining the text box in the normal flow of content.

An optimal approach would involve setting the text box dimensions to full width and height, along with consistent padding values within the primary container to maintain uniform spacing across different screen sizes.

For further clarification and demonstration of these concepts, refer to the provided code snippet and accompanying demo that showcases additional features to enhance comprehension.

View the jsFiddle demo here

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

How to Align Navigation Searchbar in Center When Bootstrap is Collapsed

I am attempting to center my search bar when it is collapsed. Currently, it appears like this: As you can see, the links are centered, but not the search bar. This is the existing HTML structure: <!-- Navigation Bar Start --> <div class ...

The onload function on the iframe is triggering twice in Internet Explorer 11

I am encountering a strange issue with an iframe in HTML that has an onload function. When using IE11, the onload function is being triggered twice, whereas it works fine in Chrome. Here is the HTML code: <iframe src="someurl" onload="someFunction( ...

I've been attempting to access the Marketo API, but unfortunately, I haven't had any luck

I've been attempting to make a Marketo API call, but I keep encountering this issue: net::ERR_NAME_NOT_RESOLVED Here is the code snippet I'm using for the function: var marketoAPIcallURL = 'https://182-EMG-811.mktorest.com/rest/v1/ ...

Dreamweaver's JSON stringify works perfectly in preview mode, but fails to function when accessed from the .AIR file after application creation

For a while now, I've been working on a basic application using Adobe AIR, specifically the HTML and JavaScript version. What this application does is submit a form to an online URL, with the form values being converted to JSON strings. In order to ...

Placing elements in Chrome compared to IE

I'm currently attempting to position elements in two rows using mathematical calculations. One of the elements, thumb_container, is a div that is absolutely positioned. Within this container, I am dynamically loading and appending image thumbnails usi ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

To change the font color to red when clicked, I must create a button using HTML, CSS, and Javascript

Currently, I am utilizing CodePen to assess my skills in creating a website. Specifically, I am focusing on the HTML component. My goal is to change the font color to blue for the phrase "Today is a beautiful sunny day!" Here is the snippet of code that I ...

What is the best way to display an alert box through AJAX technology?

My code snippet is as follows: <script> function updateQty(quantity) { $.ajax({ alert(quantity); }) } </script> Here is the corresponding HTML markup: <form name="quantityForm"> <select name="quantity" id="quantity" onChan ...

Bone structure template - optimizing list spacing with CSS

Currently, I am attempting to float my navigation bar further towards the left by at least 200px, closer to the end of the line visible below. However, every time I add a margin or padding, it causes the elements within the navigation bar to stack on top o ...

What is the most effective method for determining the distance between two UK Postcodes?

Can you suggest a reliable method for calculating the distance between two UK postcodes in order to determine if they are within range? I do not intend to display a map, but instead provide a list of results for valid locations. For example, showing loca ...

Issue with positioning of Bootstrap Nav item on the right side

I've been struggling to get my nav-items in my ul to float right. Despite trying various methods, including those outlined in this comprehensive answer: Bootstrap 4 align navbar item to the right Unfortunately, the nav item remains stubbornly stuck ...

Jquery deactivates the CSS hover effect

Having a dilemma with linked photos on my website. I have set their opacity to 0.45 by default, but want them to change to full opacity (1) when hovered over or clicked. I've implemented a JQuery function that resets the rest of the photos back to 0.4 ...

Choose an option from the drop-down menu and transfer the selected value to the following page using a hidden

Struggling to capture the selected value from a combo box and set it to a hidden field in order to retrieve it on the next page. Need some assistance with this task. Here is my form tag: <form class="well" name="ddm" id="ddm" style="margin-left: 30px; ...

The mobile devices are not showing my HTML website

I have implemented the following CSS link code on my website: <link rel="stylesheet" href="index_files/front.css" media="all" type="text/css" > Additionally, I have included the following code <meta name="HandheldFriendly" content="True"> & ...

Get ready to export your custom-designed Bootstrap material dashboard page!

I am currently using the free bootstrap material dashboard available at https://github.com/creativetimofficial/material-dashboard. I am looking to enhance it by adding an export button that allows me to export all content on the dashboard page, including ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

Is there a way for me to retrieve the widths of all child elements within an HTML document?

I have been working on a JavaScript (jQuery) function to calculate the maximum width of all child and children's-child elements within a specific div element. Here is the code I have written so far: function setBodyMinWidth(name){ var max = 0; $(nam ...

Automatic popup updates when submitting a form in a Chrome extension

Looking to develop a chrome extension popup window that, when clicked, will present a form for users to input their name and college. The goal is to save this data in chrome storage and then replace the popup with a new window displaying a greeting message ...

Can Angular be used to write data directly to a local JSON file without any other outside tools or libraries?

I've run into an issue while trying to save data to a json file after clicking "Submit" on an html formly-form using only angular. Despite knowing how to read a json file using angular, I am unsure about the process of creating files. Here is the onSu ...

Utilize PHP SVG images to trigger internal JavaScript code through the <img> tag

Here is a php function that generates an SVG image. public function actionJsTest() { header('Content-Type: image/svg+xml'); $svg = ''; $svg .= '<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/ ...