Aligning an Image Dynamically Inserted with JavaScript

I'm having trouble centering an image added via Javascript within a table using my embedded CSS. Can someone guide me on how to adjust the CSS to center the image in the table? I've tried setting the margin property to auto for the image, but it's not centering within the table.

<html>
<head>
<title>Today's Events at the TRU Union</title>
    <style>
        p {text-align: center;}
        table {display: block; margin: auto;}
        body img{display: block;margin-left:auto;margin-right:auto;}
        h2 {text-align: center; color: red;}
    </style>

</head>
<body background="Back01.jpg" text="black">
    <div id="table"></div>
</body>
<script>
        function determine_picture_day_and_month(){
            var table_content = insert_table();
            table_content += insert_title_rules_and_image();
            return table_content;
        }

        function insert_table(){
            var daily_images = ["Weekend.gif", "Monday.gif", "Tuesday.gif", "Wednesday.gif",
                            "Thursday.gif", "Friday.gif", "Weekend.gif"];
            var days = ["Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"];
            var months = ["January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"];
            var dateObject = new Date();

            var current_image = daily_images[dateObject.getDay()];
            var currentday = days[dateObject.getDay()];
            var currentmonth = months[dateObject.getMonth()];

            var table_content = "<table border='1' cellpadding='5'>"
            table_content += "<tr><td width='100'>" + currentday + 
            "</td><td><img src='" + current_image + "' /></td></tr></table>";
            table_content += "<p>Today is " + currentday + ", " + currentmonth +
                " " + dateObject.getDate() + "</p>";
            return table_content;
        }

        function insert_title_rules_and_image(){
            var table_content = "<h2>TRU Student Union Daily Schedule</h2>";
            table_content += "<hr /><img src='Events.gif' /><hr />";
            return table_content;
        }
        document.getElementById("table").innerHTML = determine_picture_day_and_month();
    </script>
</html>

Johannes provided the correct solution for this issue. Below is the updated embedded style:

     <style>
        p {text-align: center;}
        table { margin: auto;}
        body img{display: block;margin-left:auto;margin-right:auto;}
        h2 {text-align: center; color: red;}
    </style>

Answer №1

Initially, it is important to note that applying display: block to a table element goes against the typical use of tables - the tr and td elements within that table may not function as expected. Therefore, I recommend removing display: block from the CSS for table.

Furthermore, to horizontally center any inline or inline-block elements (such as images) within a table or block element, you can utilize text-align: center for that specific element.

If you want to center another block element inside a block element, it is best to specify a fixed width and use margin: 0 auto for the child element.

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 issue of overflowing scroll functionality appears to be malfunctioning

.main-content{ height: 100%; width: 60%; min-height: 800px; background-color: white; border-radius: 5px; margin-left: 1%; border: solid 1px black; } .profile-banner{ display: flex; flex-direction: row; justify-content: space-between; ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

Reducing div size when clicked - Using JQuery version 1.9

I am looking to make a specific div shrink in size, while keeping all the data visible, each time a user clicks on a certain icon with the class legend-icon. For example, I want the div with the ID #Chart to shrink when clicked. This is the HTML code: &l ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

Error encountered in PHP due to a spacing issue in the GET

<?php $current_subject = $_GET['subject_id']; $current_content = $_GET['note_id']; echo "<form method=\"post\" action=mainpage.php?subject_id=".$current_subject."&note_id=".$current_content.">"; ?> <in ...

instructions for executing this javascript within the <p> tag

This is the code I have written : <p onload=javascript:alert('sss')>www</p> Unfortunately, the code does not alert 'sss', Can someone please tell me what's wrong with my code? Thank you ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

What techniques can be used to avoid blinking while forcefully scrolling to the left?

In my previous inquiry about dynamically adding and removing divs on scroll, I was unable to find a satisfactory solution among the responses provided. However, I decided to take matters into my own hands and attempted to implement it myself. My approach ...

Enhance VideoJS using custom Ionic icons in a NextJS environment

I'm creating a platform for video content and I want to enhance the VideoJS player by incorporating icons from the Ionic set. However, as I typically use the <ion-icon/> tag to insert icons on my pages, I had to individually specify each icon&ap ...

Step by step guide to creating individual counter sections

I have set up a counter section where the numbers go from 0 to a specific value. However, currently all three counters start counting simultaneously. Is there a way for the first counter to count up first, then once it's done, move on to the second c ...

Vertical Positioning of Tabs in Materialize CSS

My current challenge involves creating vertical tabs using materialize CSS, specifically in regards to positioning. The desired outcome is for the content to align at the same level when clicking on TAB 3. An example of the expected result can be seen in t ...

Adjusting Spacing Between Characters

I've been looking for a way to convert regular characters (ABC) to full-width characters (ABC), but I haven't had any luck so far. That's why I'm turning to you guys for help. Currently, I don't have any JavaScript code writt ...

The Bootstrap navbar collapse fails to expand in the appropriate location

Whenever I try to expand the navigation on mobile mode by clicking the button, it doesn't push the content downwards. Instead, it just opens a small menu next to the button. Did I make a mistake in my code? <div class = "container"> ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

htmlEnhance your webpage with a native-like combobox

<!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get"> <input list="browsers" name="browser" placeholder="choose browser"> <datalist id="browsers"> <option value="Internet Explorer"> ...

show error notification on the user interface using asp.net mvc

What is the best way to showcase a message on a designated div element <div asp-validation-summary="All" class="text-danger"></div> when transmitting a message from the server-side? [HttpPost] public IActionResult Signup(Signup signup) ...

Implementing the class "col-xxl" is creating additional padding within the fluid container in Bootstrap

After playing around with the bootstrap grid system, I ran into a problem with the "col-xxl" class. Can anyone help me figure out why this issue occurred and how to fix it? <style> [class*="col"] { padding: 1rem; background ...

Validating the similarity of classes with JQuery

Currently, I am working on creating a quiz game using HTML, CSS, JQuery, and potentially JavaScript. I am looking to implement an if statement to check if a dropped element is placed in the correct div (city). My approach involves utilizing classes to comp ...

Leading astray — using htmlentities will not function

UPDATE (Instead of deleting this question, I'll keep it as a reminder that errors are sometimes found in unexpected places...) I apologize for leading you down the wrong path with this question. The issue causing the "Actual result" was actually loc ...

I am looking to implement a feature in my quiz application where a green tick mark appears next to the question number for the correct answer and a red cross mark for the wrong answer

My HTML code here retrieves questions from a database and displays them based on the question number. <h4>{{indexOfelement+1}}</h4>&nbsp;&nbsp; In my CSS, I need to style the questions as follows: How can I achieve this? Each question ...