Align an image in the center of a div without using absolute positioning

I'm currently facing an issue where I need to align an image at the center of a div without using absolute positioning. This is necessary because the image spills over into any adjacent divs on the page. Specifically, I have a previous div containing buttons, but the image keeps overlapping it. Is there a method to center the image without resorting to absolute positioning?

Additional context - I am working with Electron. The image in question is actually a base64 encoded image retrieved from a canvas using canvas.toDataURL(), then transferred to the main process via IPC. Subsequently, the window navigates to another HTML file and once the new page loads completely, an IPC request is made to fetch the image again. Finally, the image is embedded into an img tag on the page.

$(document).ready(function() {
    ipcRenderer.send('display-snap');
    ipcRenderer.on('reply-snap', (event, arg) => {
        $("#snapshot").attr("src", arg);
        //$("#snapshot").css('background-image', 'url(' + arg + ') no-repeat center center');
    });
});

Although setting the src attribute works as intended, the commented out code does not function as expected. I attempted to utilize a div element instead of an img tag, but the background image property of the div remains unset.

I've created a JSFiddle showcasing the desired outcome. The objective is to centrally position the image within the content div exclusively, ensuring it doesn't overlap the menu div. Both horizontal and vertical centering should be achieved for the image.

Answer №1

To center an inline element, you can utilize the CSS property text-align: center.

Check out this refreshed JSFiddle

Answer №2

To ensure the image is properly centered in the content div, it should be positioned both vertically and horizontally according to the deleted comment. It should not overlap with the menu div.

Using Flexbox can achieve this layout.

html, body {
    width:100%;
    height:100%;
    overflow:hidden;
    margin:0;
    padding: 0;
}

#menu {
    height: 64px;
    background-color: red;
}

#container {
  height:100%;
  }

#content {
  display: flex;
  height:calc(100% - 64px);
  justify-content: center; /* center horizontal */
  align-items: center; /* center vertical */
  overflow: hidden;
  background:#c0ffee
}
<body>
  <div id="container">
    <div id="menu">

    </div>
    <div id="content">
      <img id="snapshot" src="http://www.fillmurray.com/g/200/200" />
    </div>
  </div>
  <script src="scripts/window.js"></script>
</body>

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 divide an HTML string into an array using PHP

I am in need of some assistance from you all. The issue I am facing involves dealing with a string of HTML that looks like this: <h4>Some title here</h4> <p>Lorem ipsum dolor</p> (some other HTML here) <h4>Some other title ...

How can I add a label to a button group created with Bootstrap?

The Nu HTML checker is throwing an error The value of the for attribute of the label element must be the ID of a non-hidden form control. <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> & ...

Setting up bootstrap for PHP: A step-by-step guide

Struggling with integrating PHP and Bootstrap? I recently attempted to do the same, but unfortunately, my website doesn't seem to recognize Bootstrap. Instead of the sleek Bootstrap design, it's displaying a simple HTML layout. Here's a snip ...

Validation script needed for data list selection

<form action="order.php" method="post" name="myForm" id="dropdown" onsubmit="return(validate());"> <input list="From" name="From" autocomplete="off" type="text" placeholder="Starting Point"> <datalist id="From"> <option ...

What is the best way to mix up the images in my memory game?

My JavaScript memory game is functioning properly, but I would like the images to load in a random order. Unfortunately, I'm not sure how to accomplish this. Here is the current setup: var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", " ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. Issues with animation arise when you click the "Start" button again. The animation resets and begins from the start. This can be pr ...

Ways to include additional hyperlinks in my navigation bar

I am seeking ways to enhance my CSS menu so that there is no lag when new links are added. I aim to include 8 additional links if possible. Is there a way to prevent this delay and ensure that the links align correctly? nav { display: inline-block; ...

Strategies for limiting a table row in JavaScript or jQuery without utilizing the style tag or class attribute for that specific row

I am looking for a way to limit the display of records in a table. Currently, I can restrict the table rows using the style property, but this causes UI issues such as missing mouse-over effects for the entire row. I need to ensure that mouse-over functi ...

When I click on my div, the color does not change as expected

Recently, I wrote a code snippet where there are 9 different div elements each assigned a ".spaces" class. The intention was to change the color of these divs upon clicking on them. However, I encountered an issue where only the first div changes its color ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

Creating an email in Gmail with a pre-filled HTML body

Currently, I am developing a Django web application and seeking a way to enable my app to send emails via Gmail. I have explored creating a hyperlink that opens the compose window in Gmail, as well as prepopulating fields such as "to," "cc," "bcc," and bod ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

SASS: a common thread connecting multiple applications

The scenario involves a web platform that aggregates various React apps, each with its own .scss files. The goal is to extract the common .scss into a library for convenience. Any suggestions on how best to accomplish this? It's important to note that ...

Tips for presenting the cards in a professional layout

After creating a group of cards in angular using a for loop, I encountered an issue: <div class="row"> <div *ngFor="let dev_data of data" class="col-3"> <div class="card shadow"> <div class="card-body ...

Adding identifiers to columns in DataTables depending on the value of another attribute

I am facing a challenge with inserting the <span> tag into the "salesStatusName" column cell that already contains some data. This should only happen when the value of the last column, "completelyDelivered", is true. However, I do not want to display ...

What is the method for incorporating a dotted line preceding the menu options?

I am currently working on an asp.net menu that looks like this: <div id="left"> <div id="menus" runat="server"> <div id="left_menu"> <div class="abc"> < ...

Difficulty with the responsiveness of a website due to issues with the bootstrap grid system

I've been working with a Bootstrap grid that you can find at . While it works perfectly on large desktop screens, everything is a bit messy on mobile devices. The "NEW" text specifically is not visible on mobile and doesn't seem to be responsive. ...

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...

Inconsistencies in Height Among JQuery Elements

I am encountering an issue with my datatable.js, where I am attempting to limit its height based on a specific row number, such as 4.5 rows. However, I am facing a problem with the row height (tr height). For example, when using the following method with m ...

Launching a URL in a pop-up window with customized title and address bar

I am seeking to implement a feature similar to the following: <a href="post/23">post 23</a> When a user clicks on this element, I want a popup div to fade in and load the HTML from page post/23 into it. Additionally, I would like the title an ...