How to position text in the center of an image and ensure it is responsive?

I am currently in the process of trying to center the text "WHAT" over the image in col-2.

<div class="row">
  <div class="col-2">
     <div class="stackParent">
           <img class="stack-Img" src="img/base.png">
           <div class="stack-Txt">
              <div class="fourWsText stack-Txt-child">WHAT</div>
           </div>
     </div>
  </div>
  <div class="col-10">
    ...Variable length content...
  </div>
</div>

While resizing the browser, I want to ensure that the row height changes to accommodate the content in col-10. I am currently using object-fit:contain to maintain the correct image proportions. It is crucial for me to have the "stack-Txt" div resize along with the image to ensure the text remains centered over the image.

If you have any alternative methods to achieve this, please feel free to suggest.

One proposed solution involves placing the text "WHAT" in another child div, using flex properties to center the text with justify-content/align-items, and adding a window resize event listener in JavaScript to set the size of the next sibling div equal to the image.

While the provided CSS classes were utilized at some point, the most important aspect is to prevent the image from overflowing col-2 or the height, which varies based on the length of col-10.

.stackParent {
  position: relative;
  object-fit: contain;
  max-width: inherit;
  height: 20vh;
}

.stack-Txt {
  position: absolute;
  text-align: center;
  width: 100%;
  max-height: 15vh;
  min-height: 15vh;
  z-index: 4;
}

.stack-Txt-child {
}

.stack-Img {
  position: absolute;
  object-fit: contain;
  max-width: inherit;
  min-height: 15vh;
  max-height: 15vh;
  top: 0%;
  left: 0%;
  z-index: 3;
}

*Please note that there are also media queries implemented to resize text, but this should not affect the functionality.

Answer №1

To achieve the desired result using Bootstrap 5, simply utilize the predefined classes available.

  • Assign .position-relative to the main div parent
  • Use .img-fluid on the <img /> tag to ensure image responsiveness
  • Apply .position-absolute, .top-50, .start-50, and translate-middle to the stack-Txt class to centrally position it both vertically and horizontally over the image.

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c2cfcfd4d3d4d2c1d0e0958e918e93">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="row">
  <div class="col-2">
    <div class="stackParent position-relative">
      <img class="stack-Img img-fluid" src="https://source.unsplash.com/random">
      <div class="stack-Txt position-absolute top-50 start-50 translate-middle">
        <div class="fourWsText stack-Txt-child text-white">WHAT</div>
      </div>
    </div>
  </div>
  <div class="col-10">
    ...Variable length content...
  </div>
</div>

If Bootstrap 5 is not being used, simply modify the CSS according to the instructions below:

.stackParent {
  position: relative
}

/* ensure image responsiveness */
.stack-Img {
  max-width: 100%;
  height: auto;
}

.stack-Txt {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5d50504b4c4b4b455c5d1d525f5d51545a1c525f595d5c511f1e515c5d501f5a" rel="noopener noreferrer">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="row">
  <div class="col-2">
    <div class="stackParent">
      <img class="stack-Img" src="https://source.unsplash.com/random">
      <div class="stack-Txt">
        <div class="fourWsText stack-Txt-child">WHAT</div>
      </div>
    </div>
  </div>
  <div class="col-10">
    ...Variable length content...
  </div>
</div>

Answer №2

The word "what" is positioned at the center of the image regardless of the screen resolution.

.stackParent{
display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
}
.stack-Img{
position: absolute;
margin: 0;
min-height: 15vh;
max-height: 15vh;
}
.stack-Txt{
z-index: 99;
}
<div class="row">
  <div class="col-2">
     <div class="stackParent">
           <img class="stack-Img" src="img/base.png">
           <div class="stack-Txt">
              <div class="fourWsText stack-Txt-child">WHAT</div>
           </div>
     </div>
  </div>
  <div class="col-10">
    ...Content of varying length...
  </div>
</div>

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

Is Meteor.js the solution for time-triggered server requests?

We are currently in the process of developing an application that matches users from a database every Wednesday and Friday. How can we achieve this using Meteor? In the server code, I am considering organizing this functionality within a timedserver.js fi ...

Is it possible to automate a query to an API through PHP and store the results on a local drive?

Recently, I created a webpage that fetches data from an API. However, the response time from the server is quite slow, taking around 10-20 seconds to retrieve the information. To mitigate cross-domain issues, I have set up a PHP proxy for the JavaScript re ...

Building a Collapseable and Non-Collapseable Bootstrap4 NavBar in ReactJS

Is there an easy solution for creating a collapsible horizontal NavBar? <Navbar inverse fixedTop fluid collapseOnSelect> <Navbar.Header> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> ...

Add the item to an array to store its state

I have a state variable that is initially set as an empty array const [boxes, setBoxes] = useState([]); const [showAddGalley,setShowAddGalley]=useState({galleyNo:""}); I created a function to handle form submissions, where I want to update the b ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Enhancing functionality through interactive buttons: optimizing the performance of this dynamic data code

I am seeking a more efficient way to retrieve names from a database using PHP and MySQL. Currently, I have multiple if isset statements in my code, one for each button that retrieves a specific name. Is there a better approach to achieve the same result ...

AngularJS controllers and $scope are essential components in structuring and

As a newcomer to Angular, I've spent some time reading up on scopes and controllers, but I still feel like something isn't quite clicking for me. Let's take a look at this code snippet: var myApp = angular.module("myApp", []); myAp ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

My goal is to manage components asynchronously in Nuxt.js while also showcasing alert messages

My Desired Outcome I am hoping to implement a notification system that notifies the user based on the response from the server. However, since notifications are handled by a separate component, I need to asynchronously call this component in my code. The ...

Is it possible for microdata to function properly on a non-HTML5 website?

I am looking to incorporate microdata into my website, which currently does not use HTML5 but instead uses <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Although I have plans to switch ...

What is the best way to include an object within an array that is a property of another object in React.js?

Greetings, I apologize for the somewhat ambiguous title. It was a challenge to find a clearer way to express my thoughts. Currently, I am engrossed in my personal project and have encountered a particular issue. I would greatly appreciate any advice or gu ...

Sinon - the ultimate guide to intercepting the save() function in a mongoose schema

Currently, I am in the process of writing unit tests for an API that utilizes MongoDB in conjunction with mongoose for database access. Within my codebase, there exists a model file that defines and exports a mongoose model as shown below: const { Schema, ...

Is there a way to reposition the delete action to the final column within an ng2 smart table?

Is there a way to move the delete action to the last column in an 'ng2' smart table? I am looking to have the delete action appear only in the last column of my table in the ng2 smart table. Can anyone provide assistance with this matter? Below ...

What is the best method for importing several components from a directory in ReactJS?

I'm looking for a way to import multiple React components from a directory without having to export them separately in an index.js file. Here's the structure of my directory: src/ components/ comp1.js comp2.js comp3.js ...

Highcharts memory leakage issue arises when working with jQuery version 2.X

After extensive testing on my AngularJS application, I have discovered a memory leak when using Highcharts with the latest version of jQuery (2.1.4). Below are links to two plunkers for comparison: Using jQuery 1.8.2: http://plnkr.co/edit/lQ6n5Eo2wHqt35OV ...

Each time the Jquery callback function is executed, it will return just once

Whenever a user clicks on the "customize" link, I trigger a function to open a dialog box. This function includes a callback that returns an object when the user clicks "save". The problem is, each time the user clicks "customize", the object gets returned ...

Is there a way to expand jQuery quicksearch functionality to include searching for words with accents?

Hello everyone, I'm currently working on the development of this website using jQuery isotope, WordPress, and jQuery quicksearch. Everything is functioning perfectly, but I would like to enhance its functionality. For example, when I type "Mexico," I ...

Issue with Chart.js not showing up in Android Webview when animation is disabled

I am experiencing an issue with a javascript enabled WebView using a ChromeWebClient. The Chart.Js pie example displays fine until I set the options to animation: false, after which the chart stops displaying. var pieOptions = { animation : fa ...

React Router will not remount the component when using this.context.router.push

We have implemented a click handler that utilizes react router 2.0 to update the URL with this.context.router.push(). Here is the code snippet: selectRelatedJob(slug) { JobActionCreators.fetchJobPage(slug); JobsActionCreators.getRelatedJobs({'sl& ...