How to Make Radio Button Selected by Default in HTML
In this tutorial, you will learn how to make radio button selected by default in HTML. When you are creating a form, you want to create radio button groups, so that the user can select only one radio button in a given group. Radio buttons are typically small circles, which are filled when selected.
To create radio button groups, you have to use an input element with the type value of radio
, and to make the radio button selected by default, you have to use the HTML checked
attribute.
In the following example, we will make the radio button selected by default by using HTML checked attribute. Please have a look over the code example and the steps given below.
HTML
- In the HTML file, we have 3 elements (
div
,h3
, andinput
). Thediv
element is just a wrapper for the rest of the elements. - The
h3
is a heading tag with some content. - We have 2 inputs with type value
radio
to select the gender and the
first input element has achecked
attribute. As a result, the first radio button will be checked/selected by default. - In the head element, we have added a stylesheet (
style.css
) by using the link element.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Radio button selected by default</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <h3>RADIO BUTTON SELECTED BY DEFAULT</h3> <input type="radio" name="gender" value="male" checked>Male <input type="radio" name="gender" value="fmale">Female </div> </body> </html>
CSS
We are selecting the div and setting the text-align property value to center to horizontally center align the div.
div { text-align: center; }