How to position a centered div with a background image on a webpage

I am trying to achieve a centered layout for a div and its content on a webpage. The div includes a background image.

Here is my approach using Flexbox:

<head>
    <style>
        .flex_container {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
        }

        .inner {
            height: 788px;
            width: 1400px;
            background-image: url('matrix_bg.png');
            background-size: contain;
            background-repeat: no-repeat;
            color: white;
            display: flex;
            justify-content: center;
        }
    </style>
</head>

<div class="flex_container">
   <div class="inner">
      <div style="margin-top: 100px;"> Some text in the center </div>
   </div>
</div>

The output appears as shown here:
https://i.sstatic.net/DHXam.png

Although the inner text is centered on the page, I also intend for the background image to be centered. Any ideas on achieving this?


Update: Despite experimentation with different approaches, none have yielded the desired effect:

Utilizing background-position: center;: This method seems suitable, but only a portion of the image displays. My goal is to have the image scale within the parent div. https://i.sstatic.net/kNQr7.png

Applying background-size: cover: While this solution would be ideal, the challenge remains that the image is not perfectly centered. https://i.sstatic.net/pJ6PS.png

Answer №1

Your div is perfectly centered already. However, because the width of the div is larger than the image and you have applied background-size:contain, it may not appear as intended.

To improve this, you can try:

background-position: center;

or

background-size:cover;

You could also adjust the width of your inner div if needed.

<html>
<head>
    <style>
        .flex_container {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
        }

        .inner {
            height:300px;
            width: 400px;

            background-image: url('https://effortcatalyst.online/matrix_bg.png');
            
            background-size: cover;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
  <div class="flex_container">
     <div class="inner">
        <h1> Some text in the center </h1>
     </div>
  </div>
</body>
</html>

Answer №2

You can achieve image centering by using the background-position: center; property.

Here is an updated solution for centering content on a webpage:

<html>

<head>
    <style>
        .flex_container {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
        }

        .inner {
            height: 100vh;
            width: 100vw;

            background-image: url('https://effortcatalyst.online/matrix_bg.png');

            background-size: cover;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    <div class="flex_container">
        <div class="inner">
            <h1> Text centered in the middle </h1>
        </div>
    </div>
</body>

</html>

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

Dynamic content that adjusts based on a multi-row element

I'm currently designing a webpage layout with a calendar on one side and a series of information-divs on the other. In desktop view, I want the calendar to span three rows like so: CAL DIV1 CAL DIV2 CAL DIV3 Right now, I am achieving this using neste ...

Designing a search form to browse through the database by entering a specific title

I am currently working on designing a form to perform database searches for specific titles. However, I have encountered an issue where nothing happens when I try to search, possibly due to a problem with connecting to the database. The link to the appli ...

Confirm the Text Box with JavaScript

I'm struggling with validating the textbox on my login Xhtml. Once I finally cracked the code, I encountered an issue with the 'container' class in the section. How can I properly write the code and successfully validate the textbox? <h ...

Organize objects and reconstruct the inventory

I am working with a nested list that contains some string data. My goal is to iterate through the top-level items and group together those that are the same. Then, I want to split the strings inside by comma, creating separate items for each, and nest all ...

How can we make Internet Explorer 11 mimic Internet Explorer 9 in HTML?

How can I ensure that Internet Explorer 11 uses CSS styles from IE9 in my HTML? I have tried the following code: <script runat="server"> private void Page_PreRender(object sender, EventArgs e) { var meta = new HtmlMeta() ...

The text within my div is spilling over the edges despite my attempts to use text align and overflow properties

body { font-family: Arial; font-size: 15px; } .container { position: relative; max-width: 1800px; height: auto; margin: 0 auto; text-align: center; width: 90%; } .container img { vertical-align: center; } .container .content { pos ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

I am experiencing issues with my button not responding when I click on the top few pixels

I've created a StackBlitz version to illustrate the issue I'm facing. It seems like the problem might be related to my CSS for buttons... Essentially, when you click on the button at the very top few pixels, it doesn't register the click an ...

Python Selenium Timeout Exception Handling

Looking for a solution: def get_info(url): options = webdriver.ChromeOptions() options.headless = True chrome_browser = webdriver.Chrome('./chromedriver', chrome_options=options) chrome_browser.get(url) name = chrome_browser.f ...

Retrieve the current row by clicking the button

I've been struggling to retrieve a specific value from a row displayed on my PHP webpage. My objective is to obtain the current value from a particular cell in the row, but using getElementsByTagName has not been successful as it only returns an HTMLC ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

What is the process for implementing a grid with 5 columns on larger screens and 2 columns on smaller screens using reactjs?

I am currently working on building a Grid using material UI and reactJs. I found the guidelines on this link https://mui.com/system/react-grid/. However, there seems to be an issue with creating 5 columns in the grid. I attempted to create a custom grid ...

To ensure that new tabs are opened directly within jQuery UI tabs, the tab should be created within the jQuery UI tabs interface

I have integrated jquery-UI to create a dynamic Tab panel. When I click on the "Add Tab" button, a new tab is created. However, the new tab does not open automatically. It only opens when clicked on. $(function() { var tabTitle = $( ...

Having trouble with the focusout() function not registering on the search box?

When using the focusout function, I encountered an issue where clicking on a title in the search results would prevent redirecting to the title page. Although the function worked properly when closing the search results by clicking on a different element o ...

Steps for accessing the value from an input tag within the same form:

Exploring how to utilize the value "typed_from_user" in another tag within the same form, using only PHP & HTML without relying on JavaScript. Is this scenario feasible? For instance, let's say I wish to reuse the term 'pizza' <form> ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...

What is the best way to position a <td> element within a table row underneath another <td>?

Looking for a solution to ensure Content 3 appears below Content 2 in this block of HTML. Content 1 is extensive and extends far down the page. <table> <tr> <td>(Content 1)</td> <td>(Content 2)</td> ...

Is there a way for my extension to prevent a rickroll from starting before the video even begins?

I'm working on creating a Chrome extension that prevents rick rolls. Here's an overview of my manifest.json file: { "name": "AntiRick", "version": "1.0", "description": "Introduci ...

Header remains fixed when scrolling

Is there a way to make the header of a Bootstrap table fixed when scrolling, while also adjusting the width of each column based on the content within it? I want the column headers to match the width of the row with the most text. Setting the position of t ...

JQuery does not recognize $(this) after the HTML has been altered

I manage a website that includes several href links and 2 buttons that have the ability to modify those links dynamically. <div class="links"> <p class="hlCategory">Classical Mechanics</p> <ul> <li><a cl ...