Andy R Andy R - 1 year ago 58
HTML Question

Background colour for form label and radio button

I have set up a form that allows users to sort by date, Asc or Desc.

So far, I have figured out how to let a user:

1) Select a radio button.

2) Keep the radio button selected after submit.

3) Display a written message to the user of their choice.

The HTML / PHP Code:

<p>Sort by Date:</p>
<form action="" method="post" class="date">
<input type="radio" name="dateorder" onclick="javascript:submit()" value="ascending" <?php if (isset($_POST['dateorder']) && $_POST['dateorder'] == 'ascending') echo ' checked="checked"';?> /> <label for="ascending">Newset &rsaquo; Oldest</label><br><br>
<input type="radio" name="dateorder" onclick="javascript:submit()" value="descending" <?php if (isset($_POST['dateorder']) && $_POST['dateorder'] == 'descending') echo ' checked="checked"';?> /> <label for="descending">Oldest &rsaquo; Newset</label>
if (isset($_POST['dateorder'])){
echo "Date Order: " . $_POST['dateorder'];

I would like to visually show the users selection by adding a colour background when selected. The background colour should span both the radio button and label. Is this possible with CSS? So far this is what I have, only the label gets colour/style applied:

<title>Practice Radio Buttons</title>
<style type="text/css">
p{font-weight: bold;}
form input[type="radio"]:checked + label{
background-color: yellow;
padding: 10px;
border-radius: 5px;}

Answer Source

You can achieve what you're looking for, not by actually styling the radio button, but by playing around with the positioning (and padding and z-index) of the label.

  1. apply position:relative to both elements;
  2. ensure each radio button has a higher z-index than its label;
  3. apply to the label a negative margin-left value (moving it left);
  4. apply to the label a positive padding-left value (moves the label text right);

Now the left-hand side of each label is underneath its radio button.

Consequently, when you click the radio button, the highlit background will now surround the radio button and its label text.


label, input[type="radio"] {
position: relative;

input[type="radio"] {
z-index: 12;

label {
z-index: 6;
padding: 10px;
padding-left: 40px;
margin-left: -30px;
border-radius: 5px;

input[type="radio"]:checked + label {
background-color: yellow;
<form action="" method="post" class="date">
<h2>Sort by Date:</h2>

<input type="radio" name="dateorder" id="ascending" value="ascending" />
<label for="ascending">Newest &rsaquo; Oldest</label>


<input type="radio" name="dateorder" id="descending" value="descending" />
<label for="descending">Oldest &rsaquo; Newset</label>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download