How can I align Javascript output vertically in the middle?

I am currently facing an issue with a JavaScript clock displaying in a narrow frame:

<!DOCTYPE html>
<HTML>
<HEAD>
  <TITLE>Untitled</TITLE>
  <SCRIPT>
      function checkTime(i) {
        if (i < 10) {
            i = "0" + i;
        }
        return i;
      }
      function startTime() {
        var today = new Date();
        var h = today.getHours();
        var m = today.getMinutes();
        var s = today.getSeconds();
        
        m = checkTime(m);
        s = checkTime(s);
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
      }
  </SCRIPT>
</HEAD>

<BODY onload="startTime()">
  <DIV id="time" style="width: 95px; height: 32px; border: solid; border-width: thin; text-align: center"><p>time</p></DIV>
</BODY>
</HTML>

Despite setting vertical-align: middle, I cannot seem to align the content vertically within the frame. How can I achieve this?

Answer №1

The property vertical-align is only applicable to inline level and table-cell elements. Since the default display property for div is block, the vertical-align property is ignored in this case.

To achieve a similar effect, you can use line-height: 32px (equal to the height), which will help align text vertically within the div.

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  
  // add a leading zero to single-digit numbers
  m = checkTime(m);
  s = checkTime(s);
  
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
<body onload="startTime()">
  <div id="time" style="width: 95px; height: 32px; border: solid; border-width: thin; text-align: center; line-height: 32px;">
    <p>current time</p>
  </div>
</body>

Answer №2

A simple way to achieve this is by applying the CSS property line-height: 32px;. This will ensure that the line within the box matches its height, resulting in the text being centered to some extent based on the font used.

Answer №3

You may experiment with the line-height CSS property:

line-height: 32px;

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}
function startTime() {
  var current = new Date();
  var h = current.getHours();
  var m = current.getMinutes();
  var s = current.getSeconds();
  // prefix single-digit numbers with zero
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function () {
    startTime()
  }, 500);
}
startTime();
<DIV id="time" style="width: 95px; height: 32px; border: solid; border-width: thin; text-align: center; line-height: 32px;"><p>time</p></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

Struggling to forward JSON data via AJAX to Django without relying on jQuery

My goal is to utilize AJAX in conjunction with Django, but I want to achieve this without relying on jQuery. So far, I have made progress in sending URL encoded data from AJAX to Django successfully. However, I am currently facing an issue where I am unabl ...

The Parcel build was unsuccessful due to an error from @parcel/resolver-default: The file '../../../../../css/main.css' could not be loaded within the './src' directory

I utilize [email protected]. Whenever I attempt to load an external css or javascript file in my index.html, Parcel consistently fails to build with the following error: Build failed. @parcel/core: Failed to resolve './css/main.css' from & ...

Troubleshooting a problem with the navigation links on a single-page website with a

https://i.sstatic.net/5xcv9.png My website alampk.com features a single page layout with a fixed navbar at the top. However, when I click on links like exp, portfolio, etc., the section moves to the top but a portion of 50px gets covered by the navbar. I ...

Chrome timing out when sending an express post request

I am a beginner in API development and encountering an issue with a post request timing out in Chrome. The error message I keep receiving is net::ERR_EMPTY_RESPONSE. I have included my JavaScript code below where I am attempting to send data to the API. Th ...

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Tips for Creating Sand Text Effects in CSS (Using Text-Shadow)

I am attempting to create a CSS effect that resembles text written in the sand. Here is an example of what I am trying to achieve: As a newcomer to CSS, I would appreciate any guidance on how to make this effect possible. I have tried using the following ...

Transmit information from a comprehensive form using AJAX technology

I created a complex form with 30 fields, out of which 3 fields are repeated 10 times. Here's the code: <form id="artikelform" method="POST" name="controleartikelen" action=""> <table id="controle"> <tr><th>Maakartikel</ ...

Controlling multiple bx-sliders with a single pager using only JavaScript

Is there a way to control 3 sliders using the same pager? I attempted to use the following code but it did not work: <script language="javascript"> $('.mobile_left_mble,.mobile_right_mble,.text_btn').bxSlider({ //pagerCustom: '#bx- ...

Having trouble with Bootstrap 4 maintaining consistent width when affixing the sidebar

Hello there, I'm currently working with Bootstrap 4 and trying to implement affix on the sidebar. I have set up three columns for the sidebar and made them fixed under certain conditions. However, I am facing an issue where the width of the sidebar ch ...

Storing div content in database directly

I have a straightforward div that allows users to edit content on the page. I need to save this content in a database, but without including any HTML tags while still preserving line breaks. Currently, I am using the innerText property for this purpose. N ...

Monitor when a button in a grapesjs modal is clicked

When using the Grapesjs Editor, I needed a modal with a form inside it. Upon clicking the submit button, I wanted to trigger a Function that would make an ajax call. To achieve this, I attempted to create a custom component by extending it from the defaul ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Using CSS to show only the central portion of an image

How can I display only the center part of an image with dimensions height=300px and width=520px using CSS or jQuery? I tried searching on Google, but didn't find a solution. Is it possible to show only a 200x130 section from the center of an image us ...

Using JavaScript and AJAX to manage and control a shell interface

Looking to create an HTML page that includes a YouTube video and utilizes JavaScript with the YouTube API. The objective is to embed a video and test if it has been fully downloaded using the YouTube API. I have set up an Apache server with MySQL and PHP ...

Tips on displaying the appropriate object value in a text field based on the selection from a dropdown menu

In my Ruby on Rails form, I have a dropdown menu with various category names: <td> <div class="div1"> <%= f.collection_select(:category_id, Category.all, :name, id: 'category_select', :include_blank => & ...

Could the Error Detected by Siteimprove Regarding WAI-ARIA Criterion 1.3.1 be a Mistake?

When using the Siteimprove extension v. 126 for Chrome, the following HTML snippets are all showing an issue labeled "Input field has no description 1.3.1" Some may argue that a description is unnecessary because the aria-hidden attribute should effective ...

Having trouble with the placement of my footer div - seeking a solution

I've been trying to center my footer, but it keeps aligning to the left. Here's a screenshot for reference Below is the code I'm working with (core.blade.php): <div class="footer"> <div class="row align-self-end& ...

Adding an image to a Select Option label in React: A simple guide

As a newcomer to React, I am experimenting with creating a drop-down menu that includes images in the labels. My approach involves using a function to gather values from a map and construct an id: label pair to display as options in the drop-down. Both the ...

Connecting a Kendo Dropdown menu to external data sources for seamless integration

I need help with binding data to a dropdown list for my local service. Whenever I try to download the data, I keep getting an error message: Uncaught SyntaxError: Unexpected token: Does anyone have any ideas on how to resolve this issue? This is my JS ...