The challenge of vertically aligning text in a dynamically generated div

Currently, I am in the process of developing a straightforward application that allows for the dynamic addition of students and teachers.

I am dynamically adding divs with a click function.

To these dynamically created divs, I have assigned the class "userListUnit."

Below is the Javascript (JS) code:

 SchoolAdmission.prototype.display = function(nameButton) {
        var print = document.createElement("div");
        print.className = "userListUnit";
        print.innerHTML = "Name: " + this.name + ", age:" + this.age + ", department: " + this.department + "<br><br><br>";
        if (nameButton === "addStudent") {
            document.getElementById('studentList').appendChild(print);
        }
        else {
            document.getElementById('teacherList').appendChild(print);
        }
        clearFields();
    };

And here is the accompanying Cascading Style Sheets (CSS):

.userListUnit{
    vertical-align: middle;
    border: 1px solid;
    text-align: center;
    line-height: 10px;  
    box-shadow: 5px 5px 5px #888888;
    margin-bottom: 2em;
}

Here's the link to My Fiddle: http://jsfiddle.net/LPu9x/7/.

Feel free to try adding a student or a teacher and observe the vertical positioning of the text within the dynamically created div. You'll notice it's not perfectly centered vertically. Would appreciate any insights on how to resolve this issue?

Constraints:

1) Avoid using position: absolute.

2) Ensure that created divs are still displayed sequentially below one another.

Find the Updated Fiddle Solution Here: http://jsfiddle.net/LPu9x/8/

Answer №1

Give this a shot:

.userListUnit 
{
    vertical-align: middle;
    border: 1px solid;
    text-align: center;
    line-height: 15px;
    box-shadow: 5px 5px 5px #888;
    margin-bottom: 2em;
    padding-top: 5px;
    height: 30px;
}

If you need to make adjustments, just tweak the line-height...

Take a look here

Answer №2

If you prefer changing the block element div to an inline element like p, you can do so and the vertical-align property will function as expected. Remember to remove any nested br tags since CSS should handle spacing with properties such as padding or margin.

Here's how your script would look after changing the tag to a p:

SchoolAdmission.prototype.display = function(nameButton) {
    var print = document.createElement("p"); // now using p tag
    print.className = "userListUnit";
    print.innerHTML = "Name: " + this.name + ", age:" + this.age + ", depart: " + this.department;
    if (nameButton === "addStudent") {
        document.getElementById('studentList').appendChild(print);
    }
    else {
        document.getElementById('teacherList').appendChild(print);
    }
    clearFields();
};

To adjust vertical alignment, change the CSS line-height to a larger value like 30px (since we removed the br tags):

.userListUnit{
    vertical-align: middle;
    border: 1px solid;
    text-align: center;
    line-height: 30px;  
    box-shadow: 5px 5px 5px #888888;
    margin-bottom: 2em;
}

That's it! By adjusting the line-height attribute, the text will always be vertically aligned.


DEMO - Try out the in-line tag with vertical-align


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

Initial argument for the event listener

If I have event handlers registered inline in my markup (even though it's deprecated) like span id="..." onclick="foo(p1,p2,p3)" how do I access the "event" object in the event handler function foo? Is changing the above to span ...

Is it possible to perform advanced SQL-like queries on JSON data using JavaScript?

Lately, I've been faced with a challenge where I need to manipulate a JSON result using SQL commands like left joins, sum, and group by. Has anyone else come across this issue recently? I'm currently experimenting with the jsonsql JavaScript libr ...

Using RxJS v5 for Sending a POST Request with Parameters

Snippet of my RxJS code: .mergeMap(action => { const user = store.getState().user; return ajax.post(`${config.API_BASE_URL}/api/v1/rsvps`, { rsvp: { meetup_id: action.payload, user_id: user.id, } }) .map(action => calenda ...

Using jQuery Validation for implementing a step-by-step validation process in a wizard form

Looking for a way to implement the jQuery Validation Plugin in conjunction with jQuery UI Tabs? How can I use the jQuery Validation Plugin to validate each step triggered by the next button when using tabs? Most examples of the jQuery Validation Plugin foc ...

Styling for the DataTable disappears upon loading jQuery

my PHP file named "zero3data.php" <?php printf('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">'); printf('<thead>'); printf('<tr>'); ...

Automate the login process for a website and programmatically fill out and submit a form

I am currently trying to automate the login process on Skype's website using Selenium in C#. Everything goes smoothly until I reach the password field, which seems to be elusive to Selenium. I have tried various methods to locate the password field bu ...

Is it possible to use JavaScript to forcefully transition a CSS keyframe animation to its end state?

One dilemma I am facing involves CSS keyframe animations triggered by scroll behavior. When users scroll too quickly, I would like JavaScript to help send some of the animations to their 'finished/final' state, especially since the animations bui ...

Using the power of HTML5, store data locally on

I am curious about the possibility of using local storage on a different page. I want to track clicks made on one page and display it on another, but I'm not sure how to go about it or if it's even feasible. Any help you can provide would be grea ...

I need assistance improving my poor JavaScript patterns and practices. Where should I turn for help?

After focusing primarily on back-end tasks for the past few years, it's become apparent to me that JavaScript (and CoffeeScript) projects have evolved significantly in my absence. Working mainly in a rails environment, my previous JavaScript/jQuery i ...

Issues with clicking on the ion-tab icon in AngularJS are hindering the functionality

I'm currently facing a challenge with an ion-tab icon in my AngularJS project. I've been attempting to add a click action using the code below, but unfortunately, nothing is displaying as expected. HTML <ion-tab title="Share" icon="icon ion- ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...

Issue encountered while adding platform in Cordova version 8.1.2

Attempting to set up a new Cordova project. The version of Cordova being used is 8.1.2 ([email protected]). I ran the cordova create command and it was successful. However, when trying to add the Android platform with the command cordova platform add ...

What is the process for translating symbols in a URL or text into hexadecimal characters? (e.g. changing = to %3D)

Currently, my script in use is extracting variables from URL parameters using jQuery. The value it retrieves happens to be a URL. For instance, if the URL is as follows: http://localhost/index.html?url=http://www.example.com/index.php?something=some the ...

The checkbox is not updating as anticipated

I'm currently developing a basic widget that allows the user to change the value of either the check box OR the entire div by selecting them. Below is the code I have implemented: $(document).ready(function() { $(document).on("click", ".inputChec ...

Animate images using mouse vertical movement

Creating websites is just a hobby for me, not something professional. Recently, I came across a beautifully designed website that had some unique features I hadn't seen before, like placing three images in one div (which I researched and learned how t ...

What are some strategies for establishing communication between sibling components in Vue?

Currently, my Vue app has a structure that includes a "blackout" component for displaying modals and a router-view for various sub-menus. These components are siblings at the same level. <blackout v-if="this.popup.currentPopup"></blacko ...

Issue with clicking a button in Selenium using JavaScript for automation

I'm encountering an issue where Selenium is detecting an element as disabled, despite it being enabled. To work around this, I am attempting to click on the element using JavaScript with the following code snippet: IWebElement button = driver.FindEl ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

Leverage the Power of Mongoose Schema Across Various Files (mongoose)

I recently encountered an issue while trying to utilize my Permissions schema in two different files. The error message "Cannot overwrite 'example' model once compiled" keeps popping up. Query: How can I effectively employ my Permissions schema ...

`Slide bootstrap carousel without moving other elements`

.carousel { position: relative; height: 500px; .carousel-inner .item { height: 500px; } .carousel-indicators > li { margin: 0 2px; background-color: $maincolor; border-color: $maincolor; opacity: .7; ...