Use CSS3 and jQuery.validate to highlight mandatory fields in red

I've been attempting to change the color of required fields in a form to red, but so far I haven't had any success. Here is the form code and the CSS that I have experimented with.

contact.html

                        <h2>Send us an email...</h2>
                        <br/>
                        <ul>

                            <li>
                                <label for="senderName"  >Your Name</label>
                                <input type="text" name="senderName" id="senderName" required="required" placeholder="Please type your name"   maxlength="40" />
                            </li>

                            <li>
                                <label for="senderEmail" >Your Email Address</label>
                                <input type="email" name="senderEmail" id="senderEmail" required="required"  placeholder="Please type your email address"   maxlength="50" />
                            </li>

                            <li>
                                <label for="message" style="padding-top: .5em;" >Your Message</label>
                                <textarea name="message" id="message" placeholder="Please type your message" required="required" cols="80" rows="10" maxlength="10000"></textarea>
                            </li>

                        </ul>
                        <div id="formButtons">
                            <input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
                            <input type="button" id="cancel" name="cancel" value="Cancel" />
                        </div>
                    </form>

style.css

label[required=required]{
    color: darkred;
}

label[] > input[required="required"] {
    background: red;  }

Answer №1

In the scenario where the <input> element is required and comes after the <label>, a previous sibling selector in CSS would be ideal. Unfortunately, CSS does not provide a way to select elements backwards, only forwards.

To overcome this limitation, you could rearrange your HTML so that the <label> appears after the <input>. Once this adjustment is made, you can use the + selector like so:

input[required]+label {
    background: red;
}

If changing the HTML structure is not an option, another solution would be to add a specific class to the label element, for example:

<label class="required">...</label>
.

For further information on this topic, you may find this related question helpful: Opposite of adjacent sibling selector?

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

Weird Chrome behaviors with CSS3 animations

I have been working on a CSS3 animation that involves rotating a div with an image in the background. My goal is to have the same animation play at a different speed when the user hovers over the element. Here is the code snippet I have been using: .roc ...

Exploring Font Choices: Customizing Your Text Style

I've been attempting to incorporate my own font into my website, but despite researching several Stack Overflow articles, I'm facing various browser-specific and path-related issues. Sadly, I haven't been able to successfully display my font ...

What is the best way to place tfoot at the top of the table

Below is the structure of my table: https://i.stack.imgur.com/QmlVn.png In the table, there are search input fields at the bottom of each column. I would like to move them to the top, right after the <thead> </thead>. The basic HTML code for ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

Utilizing Jquery and Ajax to create a dynamic dropdown selection feature based on dependencies from a JSON file

Could you assist with the code snippet below? I have a form where each dropdown list depends on the selection above it. Based on the user's selection, the appropriate data should display in the subsequent dropdown list. I am trying to make dropdown l ...

A guide on seamlessly transitioning from a mobile website to the corresponding native app

I am currently working on a mobile website project. This website is built using basic HTML and is accessed through a URL on a web browser, not as a native app or through PhoneGap. The client has requested links to their Facebook, Pinterest, YouTube, Twitt ...

Guide to developing JavaScript code that moves information from one local website to a different one

Here's the scenario: You input text into a field on website A and click a button. Upon clicking that button, the entered text should appear in website B. I attempted to use localStorage for this functionality, but unfortunately it was not successful. ...

Could you advise on the best placement for my upcoming JQuery animation?

Here is the code I am currently working with: $(function() { $("button").click(function() { $("#box1").animate({ left: $(window).width() - 800 }, { complete: function() { $("#box1").hide(); } }); $("#box2").a ...

Implementing a delay between two div elements using jQuery

I have two Divs with the class "sliced", each containing three images with the class "tile". When I animate using jQuery, I am unable to add a delay between the "sliced" classes. However, I have successfully added a delay between the "tile" classes. index ...

Instructions for submitting information from a web form using Python without needing to know the form's ID or name

I am currently attempting to automate the submission of data into the online forms found on this webpage: Unfortunately, I am unable to determine the specific names of these forms by inspecting the source code. I have tried using the requests python modul ...

What could be causing my jQuery to malfunction after I include the .sqrt() function?

Seeking assistance in creating a grid of divs, I am working on finding the square root of the user's input to determine the height and width required to form a square. The code below is what I currently have: $('#size').click(function(){ $ ...

Click on the header to activate the accordion link with a trigger

I am having an issue with a trigger. My goal is to make the accordions collapse not only by clicking on the link, but also by clicking on the entire header panel. Below is my header's code: <div class="accordion-head" role="tab"> <div cl ...

Pictures without a set width

Hey there! I'm working on a responsive website and facing an issue with image resizing. When I shrink the screen size, the images also shrink along with it. How can I set a fixed width for the images? I tried switching from rem to px but that didn&apo ...

Guide on implementing event listener for right click using pure JavaScript (VANILLA JS)

I need the div to appear wherever the cursor is holding down the right mouse button. In my scenario, I am using the following code: <div class="d-none" id="item"></div> #item{ position: absolute; top: 0; left: 0; w ...

Align Bootstrap list items vertically

I'm facing a challenge with aligning the yellow list item blocks vertically in my design. The issue arises because the black dog item is not aligning properly due to its image being shorter than the other two blocks. I've been struggling to find ...

Change the color of the border to match the background color

I have a parent container with a unique background color. Inside the parent container, there is an unordered list (ul) with multiple list items (li), each having a distinct color and a brighter border color. Now, I am looking to extract the border color of ...

photos arranged in rows rather than a single row

Looking for help with arranging the remaining photos in the second row? Check out this example image link. I'm struggling to organize a row of overflow images within the "small-img-row" division. This row is located under the main image in col-2. H ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

Creating a fluid side navigation bar in reactjs

Can someone please help me with the following code issue? I am encountering an error related to the script tag when running it in ReactJS, although it works fine in a simple HTML file. Upon starting npm, an error is displayed pointing to line number which ...

Can you explain the guidelines for overlapping CSS media queries?

When it comes to spacing out media queries accurately to prevent overlap, how should we approach it? Let's examine the following code as an example: @media (max-width: 20em) { /* styles for narrow viewport */ } @media (min-width: 20em) and (max ...