Achieving consistent text alignment in HTML and CSS without relying on tables

As I delve into the world of HTML and CSS, I've taken a traditional approach by crafting a login page complete with three input controls (two text inputs and one button). To ensure proper alignment of these elements, I initially turned to the trusty <table></table>. However, I recently stumbled upon information suggesting that using tables for layout is not recommended. Here's what my current setup looks like:

Home.html

<div>
    <table>
        <thead>
            <tr><th><span>Login Page</span></th></tr>
        </thead>
        <tbody>
            <tr>
            <th><label>Username:</label></th>
            <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <th><label>Password:</label></th>
                <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <td><input type="button" value="Submit" /></td>
            </tr>
        </tbody>
    </table>
</div>

Despite the convenience offered by tables in aligning input fields, I've decided to explore alternative methods leveraging basic CSS techniques to achieve the same result without relying on tables. The following snippet showcases my endeavor:

Home.html

<div class="box">
    <span>Login Page</span>
    <br />
    <span>
        <label>Username:</label>
        <input type="text" value="" />
        <br />
        <label>Password:</label>
        <input type="text" value="" />
        <br />
        <input type="button" value="Submit" />
    </span>
</div>

style.css

.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}

While the CSS solution has successfully aligned the input controls, it necessitates the use of multiple break tags (<br />) along with additional code for alignment that could be achieved more efficiently using the <table> tag. Seeking guidance on the most standard approach moving forward and whether my current trajectory reflects best practices.

Answer №1

@JohnDoe Take a look at the code snippet below, which demonstrates how to create a login page layout without relying on tables. Additionally, I recommend considering the use of Bootstrap framework for your projects.

.main_container{
  width:100%;
  }
  .inner_box {
 margin: 40px auto;
 width: 30%;
  }
  
  .inner_box span{
 clear: both;
 display: block;
  }
  .inner_box span:first-child{
  margin-bottom:10px;
  }
  .inner_box span:nth-child(n+2){
  margin-bottom:20px;
  }
<div class="main_container">
<div class="inner_box">
            <span>Login Page</span>
            <span>
                <label>Username:</label>
                <input type="text" value="" />
            </span>
            <span>    
                <label>Password:</label>
                <input type="password" value="" />
            </span>
            <span>                
                <input type="submit" value="Submit" />
            </span>
    </div> 
</div>

Answer №2

While tables are commonly used for forms, I find CSS tables to be a much simpler and more efficient method.

Take a look at the code snippet below:

form {
  display: table;
}

p {
  display: table-row;
}

label {
  display: table-cell;
}

input {
  display: table-cell;
}
<form>
  <p>
    <label for="a">Short label:</label>
    <input id="a" type="text">
  </p>
  <p>
    <label for="b">Very very very long label:</label>
    <input id="b" type="text">
  </p>
</form>

Answer №3

Just a small suggestion to add on to what has already been mentioned - have you considered using a separate container for each form control along with its label? Here's an example:

<form>
    <div class="input-group">
        <label for="name">Username:</label>
        <input type="text" id="name" value="" />
    </div>
    <div class="input-group">
        <label for="password">Password:</label>
      <input type="text" id="password" value="" />
    </div>
</form>

Some may argue that this is unnecessary, but I believe it offers more flexibility in terms of positioning. However, Michael Seltenreich makes a valid point. Despite that, tables are still commonly used for forms in various places, although personally, I prefer avoiding this approach.

P.S. If you want to arrange labels and inputs side by side, you might want to consider using flexboxes.

Answer №4

Avoid using tables whenever possible. One alternative approach is to:

   <div class="form-wrap">
     <h2>Login Form</h2>
     <div class="form-field">
       <label>User Name</label>
       <input type="text" value="" />
     </div>
     <div class="form-field">
       <label>Password</label>
       <input type="text" value="" />
     </div>
     <input type="button" value="Submit" />
    </div>

CSS:

.form-field label {
  width: 80px;
  display: inline-block;
}
.form-field {
  margin-bottom: 10px;
}

Check out the codepen link

Answer №5

While tables may not be the best choice for all situations, they are well-suited for forms like the one you're attempting to design.

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

IE9 causing trouble with CSS vertical alignment

I'm trying to center a button with text using Cuffon for the font, but I can't get it to align vertically and horizontally. The text-align property is working fine, but vertical align isn't. Here's the code for my div block: btndownlo ...

Is it recommended to place the styles created by material-ui for child components after the styles generated for the parent component?

Utilizing material-ui, which utilizes JSS for styling a website. I have a component named Layout that applies margin to all its children (using the all children selector & > * in its style). This functionality works, but I would also like the child ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

Issue with React container not connecting properly

I am currently facing an issue with a search bar where the input value is not displaying properly. Even when I check the value in the console, it only shows one character at a time. https://i.stack.imgur.com/Qm0Lt.png My assumption is that there might be ...

Is there a possible method to obtain a smartphone number from a website?

Seeking a solution to retrieve the phone number of a device using HTML 5, JavaScript, or similar technology. Recently, I successfully obtained the coordinates of the device by incorporating the following JavaScript code: <!DOCTYPE html> <html> ...

What is the best way to create a reusable component for this particular version of Autocomplete?

Can anyone help me figure out how to make this Autocomplete component reusable? I am using it multiple times but struggling with defining the necessary useStates. <Autocomplete required value={firstName} onChange={(event, newV ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

How can strings of dates be arranged in MM/DD/YYYY order?

Is there a correct way to sort these dates in descending order? I've attempted using arr.sort() and arr.sort().reverse(), searched extensively on stack overflow, but still cannot find a solution. Every attempt at sorting them seems to be incorrect. [ ...

Unable to access property 'name' of null object

I'm currently learning how to build a local library app using Express with The Odin Project's tutorial. Below are the relevant parts of my code: In routes/catalog.js, I have this: router.get("/books", book_controller.book_list); In models/book. ...

What's the reason behind this file not opening?

When I try to insert this code into files index.html, style.css, and app.js, the page refuses to open. The browser constantly displays a message saying "The webpage was reloaded because a problem occurred." I am using a MacBook Air with macOS Big Sur and a ...

eliminate the offspring of a component (chessboard)

Hey there! I'm currently working on developing a chess game and I could really use your expertise to help me solve an issue. In my code, when I try to move a piece in the game, this is what happens: 1. First, I remove the existing piece from its cu ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

Utilize Vue.js to send bound data to a click event

I am currently working with a v-for loop that iterates over data fetched from an API, setting the key as the ID of each object. My goal is to create a click event that captures the v-bind:key value of the clicked element. This will allow me to locate all t ...

Executing commands following a JSON loop in jQuery

I'm experiencing an issue with jQuery. When my page loads, I fetch a JSON file and loop through its items. However, I am unable to attach any event listeners to the input button that is added. For instance, I want to display an alert message... It s ...

Minimize the size of the MUI date selector widget

I've been incorporating the MUI date picker into a data list, but I'm looking to decrease the height of the input field and adjust the positioning of the close date and calendar icons. They're currently taking up too much space between them ...

-moz-box-reflect - Styling for FireFox

I've been attempting to achieve a similar effect to this tutorial at http://designshack.net/tutorialexamples/HoverEffects/Ex5.html. However, I'm encountering issues with getting the reflection of the image to display properly in IE and Firefox. H ...

Vue.js template is failing to properly render hyperlinks, although basic string output is functioning as expected

Whenever I print attrib.link, everything works perfectly fine, <div v-for="attrib in attributes"> {{ attrib.link }} </div> However, when I try: <div v-for="attrib in attributes"> <a target='_blank' href={{ attrib.link } ...

Left align the CSS menu text next to the menu image

Currently, I have a basic CSS menu that includes background images aligned to the left. My goal is to have the text float to the left of each image as well. <div class='mmenu'><ul><li><a id="li6" class="menu-news" href= "vie ...