How to properly align labels with input fields using CSS

I'm facing a design challenge with my form, showcased in this fiddle: https://jsfiddle.net/ejkvp88v/2/. The inputs are centered, which is great, but I'm struggling to align the labels above the inputs on the left side. I've searched through S.O. for solutions without success. Can anyone provide guidance on achieving this? My HTML and CSS are included below.

In essence, I want the form inputs to stay centered while the labels are positioned above them aligned to the left.

Here's the structure of the form:

<div class="container">
<div class="base-template">
    <h1>A form whose labels need some aligning</h1>

    <p class="lead">Use the form below to submit some information.</p>
</div>
<div class="container">
    <div class="table-responsive">
        <div class="request-form-container">
            <form action="" method="post" accept-charset="utf-8">
                <label for="email" class="formLabel">E-Mail Address</label>
                <br />
                <input type="text" name="email" value="" id="email" size="30" />
                <br />
                <br />
                <label for="firstName" class="formLabel">First Name</label>
                <br />
                <input type="text" name="firstName" value="" id="firstName" size="30" />
                <br />
                <br />
                <label for="lastName" class="formLabel">Last Name</label>
                <br />
                <input type="text" name="lastName" value="" id="lastName" size="30" />
                <br />
                <br />
                <button name="" type="submit" id="submitButton" class="btn btn-default btn-default">Submit&nbsp;<span class="glyphicon glyphicon-transfer"></span>
                </button>
            </form>
        </div>
    </div>
</div>

Below is the CSS file where I've made customizations specific to this project alongside Bootstrap styles.

body {
padding-top: 50px;
}

.base-template {
padding: 40px 15px;
text-align: center;
color: #060a84;
}
a {
color: #060a84;
}
.formLabel {
color: #060a84;
}
.request-form-container {
padding: 0.5em;
margin-left: auto;
margin-right: auto;
width: 100%;
text-align: center;
}
.successMessage {
text-align: center;
}
.submitFormContainer {
margin-top: 1.6em;
}
#navbar {
background-color: #525eab;
}
.navbar-inverse {
background-color: #525eab;
}
.nav-bar-fixed-top {
background-color: #525eab;
}
.navbar-inverse .navbar-brand {
color: white;
}
.error {
color: red;
font-weight: bold;
font-size: 1.1em;
}

Lastly, here's a mockup image created in Photoshop illustrating how I envision the form layout.

Answer №1

To achieve the desired outcome, a simple solution is to enclose each label and input field within a div element and apply the text-align: center style to that specific element. By styling the wrapper properly, you can make it behave like an inline element, enabling the centering effect.

This method eliminates the need to specify widths for individual elements, making it more adaptable for various screen sizes.

<div class='input-wrapper'>
  <label for="email" class="formLabel">E-Mail Address</label>
  <br />
  <input type="text" name="email" value="" id="email" size="30" />
</div>

Next, add the following CSS style:

.input-wrapper {
  display: inline-block;
  text-align: left;
}

For a demonstration, check out this example: https://jsfiddle.net/ta0pesyb/

Answer №2

To ensure proper alignment, enclose your fields within a container such as a span or div. Center the container while keeping the fields left-aligned inside it. This method will facilitate easy label alignment with the field below.

Answer №3

To easily center content, wrap it in a container with a specified width, then utilize the margin: auto rule for centering.

Maintain the default text alignment (left), and modify the width of the container based on the positioning of your inputs.

Example: https://jsfiddle.net/ejkvp88v/4/

.form-wrapper{
    width: 400px;
    margin:  auto;
    text-align: left;
}

Answer №4

One way to address this issue is by utilizing the display property with a value of inline-block and aligning the label text to the left. However, it is necessary to specify the width of the label text. To implement this solution, include the following CSS code:

label { display: inline-block; width: 245px; text-align: left; }

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

What's the secret behind the functionality of this jQuery menu?

As I was browsing the website , I noticed that they have a menu in the top header with links like "Freebies" and "Inspiration". I searched for where the code for this menu is located, but couldn't find it. Can anyone help me locate the code? I' ...

Issue with JavaScript variables (I presume) - there seems to be a conflict when one variable is used alongside another

I am attempting to conduct a test that requires displaying the number of attempts (each time the button is pressed) alongside the percentage of successful attempts, updating each time the button is clicked. However, I've encountered an issue where onl ...

Copy values of multiple input fields to clipboard on click

I have a collection of buttons in my Library, each with different text that I want to copy when clicked function copyTextToClipboard(id) { var textElement = document.getElementById(id); textElement.select(); navigator.clipboard.writeText(textElement. ...

The table toggle feature seems to be malfunctioning in Safari, whereas it works perfectly in Chrome

My table includes a td element that serves as a toggle switch, transitioning between 3 states flawlessly in Chrome. However, I am facing issues with its functionality in Safari and seek assistance in rectifying the issue to ensure cross-browser compatibili ...

The use of script src with vue.js is causing issues

I am looking to move my Vue code into an external .js file. Since I am new to Vue, I am trying to keep it simple without using webpack. However, I have encountered an issue where Vue does not work when using the script src tag in the html file. For instanc ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

Utilize images inputted via an HTML DOM file uploader within p5.js

I'm facing a challenge with allowing users to upload their image file through a DOM file uploader (<input type="file"></input>). Once the image is uploaded, I'm unsure of how to transfer it to JavaScript and process it using p5.js. Ho ...

Is there a way to lower just one border?

I need assistance with moving the .container div downward on my webpage. I attempted using (margin-top: 30px) and it worked, but unfortunately, it also shifted down the border of the (.container) along with the outline of .all. My goal is to have only the ...

"Encountering difficulties with certain images not loading in the keyframe slide show feature on IOS

Ensure that the image in the slide show is preloaded, followed by preloading each additional image before transitioning to the next key frame. Finally, preload the original image for the final display. I even attempted changing the last image, but encounte ...

When the Bootstrap navbar is collapsed, clicking on it does not result in it opening

I'm attempting to create a collapsible navbar for smaller screens that expands when a button is clicked. However, upon clicking the button, nothing happens and I'm unsure why. <nav class="navbar navbar-expand-lg navbar-light" style="backgro ...

Best methods for deleting an element's attribute or style attribute

Imagine this snippet of CSS code: .notif-icon { display: inline-block; } In my HTML, I have the following element which starts off hidden by overriding the display property of the notif-icon class: <span id="error" class="notif-icon& ...

Boost website performance with Google Page Speed by optimizing CSS above the fold using this innovative Bootstrap Template Plugin

My Google PageSpeed Insights report suggests that I should place my CSS below the fold. However, Bootstrap is being used as my templating plugin. I am contemplating printing bootstrap.min.css inline on my homepage, but I hesitate because it may lead to i ...

Obtaining solely the words found within HTML documents

In my Python 2.7 project, I have a folder containing multiple HTML pages that I need to extract only words from. My current process involves opening the HTML file, using the Beautiful Soup library to extract text, and then writing it to a new file. However ...

Generating a PDF from a CSS3 multi-column layout with the help of snappy (a wrapper for wkhtmltopdf)

I am attempting to create a PDF with three columns using barryvdh/laravel-snappy and wkhtmltopdf. Since the text that will populate these columns varies in length, I need a method that allows the text to flow freely within the columns. I have attempted to ...

Different width, same height - images arranged side by side in a responsive layout

The problem lies in the images: https://i.sstatic.net/rydNO.png Here is an example of desktop resolution: https://i.sstatic.net/uv6KT.png I need to use default size pictures (800x450px) on the server. This means I have to resize and crop them with CSS to ...

Failure to correctly apply CSS to Angular custom components causes styling issues

I have been working with a custom component and I have incorporated several instances of it within the parent markup. When I apply styles directly within the custom component, everything works as intended. However, when I try to set styles in the parent co ...

Create a variety of colors with a simple click

A form has been created for the footer where clicking on an input causes the text and border-bottom to transition from grey to white. Visit Code Pen HTML: <div class="footer"> <div class="footerContainer"> <form> <inp ...

Using CSS to align the position of a div with the last word position of an h4 element

Trying to figure out how to position a div at the end of an h4 text element has been challenging. When the h4 text is on a single line, it's easy to place the div correctly. However, things get complicated when the text spans multiple lines. In that c ...

Is it possible to convert a blob to an image file using the FileReader in HTML

client side code <head> <script> var reader = new FileReader(); var objVal; var image = new Image(); reader.onload = function(e) { document.getElementById('propertyImg').setAttribute('src', e.target.result); }; fun ...

What is the best way to turn off autocorrect in a textarea on IE11 without turning off spellcheck?

In my experience, disabling the spellcheck attribute seems to solve the auto-correct issue, but it also eliminates the underlining of misspelled words. <textarea id="TextArea1" spellcheck="false"></textarea> I prefer to keep spellcheck enabl ...