Align radio buttons

Hi , hope all is good. i was wondering if someone could have a butchers at an issue i’m having centering radio buttons and their respective labels.
I’ve been playing around with a form to learn css html js and have added a few bells and whistles to it . i seem to have hit a stumbling block with the alignment of the forms radio buttons and labels no matter what i try i cant keep them vertically aligned. I hadnt noticed until now as the text had been all the same in each division , it wasnt until i added real text that i noticed it didnt line up. Could someone point me in the right direction on aligning these radio buttons centrally, i can get them to line up to the left…thanks

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Matrix Style Quiz</title>
    <style>
<!-- @import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap'); -->

body {
    font-family: 'Share Tech Mono', monospace;
    background-color: #000;
    color: #00FF00;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.container {
    background-color: rgba(0, 0, 0, 0.8);
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 255, 0, 0.5);
    width: 100%;
    max-width: 800px;
    overflow-y: auto;
    max-height: 90vh;
    text-align: center;
}
h1 {
    text-align: center;
    color: #00FF00;
}
.question {
    margin-bottom: 20px;
	text-align: center;
}
.question p {
    font-weight: bold;
    color: #00FF00;
}
.options {
    display: flex;
    flex-direction: column; /* Align items vertically */
    align-items: center; /* Center align the items horizontally */
}
.options label {
    display: flex;
    align-items: left; /* Center align the label and input */
    margin-bottom: 5px;
    cursor: pointer;
}
.options input[type="radio"] {
    margin-left: 20px; /* Space between the radio button and the label text */
	align-items: center;
width:100%;
}
.text-input {
    margin-bottom: 20px; 
}
.text-input label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #00FF00;
}
.text-input input[type="text"] {
    width: 80%;
    padding: 10px;
    border: 1px solid #00FF00;
    border-radius: 5px;
    background-color: #000;
    color: #00FF00;
}
button {
    display: block;
    width: 100%;
    padding: 10px;
    background-color: #00FF00;
    color: #000;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
}
button:hover {
    background-color: #00cc00;
}
.error {
    border: 2px solid red;
}
::-webkit-scrollbar {
    width: 12px;
}
::-webkit-scrollbar-track {
    background: #000;
}
::-webkit-scrollbar-thumb {
    background-color: #00FF00;
    border-radius: 10px;
    border: 3px solid #000;
}
.keyboard {
    display: none;
    position: absolute;
    background-color: green;
    border: 1px solid white;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    padding: 10px;
    z-index: 10;
    flex-wrap: wrap;
    width: auto;
    max-width: 700px;
}
.key {
    padding: 10px;
    margin: 5px;
    background-color: black;
    border: 1px solid white;
    border-radius: 15px;
    cursor: pointer;
    user-select: none;
    flex: 1 0 10%;
    text-align: center;
    font-size: 18px;
}
.key:hover {
    background-color: #00cc00;
}
.row {
    display: flex;
    width: 100%;
    justify-content: center;
}
input {
    padding: 10px;
    font-size: 26px;
    margin-top: 10px;
}
.error {
    border: 2px solid red;
}


    </style>
</head>
<body>

   
<div class="container"> 
    <h1>Matrix Style Quiz</h1>
    <form id="quizForm">
        <div id="questionsContainer"></div>


        <div class="text-input">
            <label for="input1">Input 1a:</label>
            <input type="text" id="input1" name="input1">
        </div>
        <div class="text-input">
            <label for="input2">Input 2a:</label>
            <input type="text" id="input2" name="input2">
        </div>
        <div class="text-input">
            <label for="input3">Input 3a:</label>
            <input type="text" id="input3" name="input3">
        </div>
        <button type="button" onclick="submitQuiz()">Submit</button>
    </form>
    <div id="results"></div> <!-- New div for displaying results -->
</div>



    <div class="keyboard" id="keyboard">
        <!-- Row 1: Numbers -->
        <div class="row">
            <div class="key">1</div>
            <div class="key">2</div>
            <div class="key">3</div>
            <div class="key">4</div>
            <div class="key">5</div>
            <div class="key">6</div>
            <div class="key">7</div>
            <div class="key">8</div>
            <div class="key">9</div>
            <div class="key">0</div>
        </div>
        <!-- Row 2: Letters Q-P -->
        <div class="row">
            <div class="key">Q</div>
            <div class="key">W</div>
            <div class="key">E</div>
            <div class="key">R</div>
            <div class="key">T</div>
            <div class="key">Y</div>
            <div class="key">U</div>
            <div class="key">I</div>
            <div class="key">O</div>
            <div class="key">P</div>
        </div>
        <!-- Row 3: Letters A-L -->
        <div class="row">
            <div class="key">A</div>
            <div class="key">S</div>
            <div class="key">D</div>
            <div class="key">F</div>
            <div class="key">G</div>
            <div class="key">H</div>
            <div class="key">J</div>
            <div class="key">K</div>
            <div class="key">L</div>
        </div>
        <!-- Row 4: Letters Z-M, Symbols, Space, Backspace -->
        <div class="row">
            <div class="key">Z</div>
            <div class="key">X</div>
            <div class="key">C</div>
            <div class="key">V</div>
            <div class="key">B</div>
            <div class="key">N</div>
            <div class="key">M</div>
            <div class="key">Backspace</div>
	    
        </div>
    </div>

    <script>

let activeInput = null;
const inputs = document.querySelectorAll('input[type="text"]');
const keyboard = document.getElementById('keyboard');

inputs.forEach(input => {
    input.addEventListener('focus', () => {
        activeInput = input;
        const rect = input.getBoundingClientRect();
        keyboard.style.display = 'flex';
        keyboard.style.position = 'absolute';
        keyboard.style.left = `${rect.left}px`;
        keyboard.style.top = `${rect.top - keyboard.offsetHeight}px`; // Position above the input
    });
});

const keys = document.querySelectorAll('.key');
keys.forEach(key => {
    key.addEventListener('click', (event) => {
        event.preventDefault();
        if (activeInput) {
            if (key.textContent === 'Backspace') {
                activeInput.value = activeInput.value.slice(0, -1);
            } else {
                activeInput.value += key.textContent;
            }
        }
    });
});

document.addEventListener('click', (event) => {
    if (!keyboard.contains(event.target) && !Array.from(inputs).includes(event.target)) {
        keyboard.style.display = 'none';
        activeInput = null;
    }
});



 const questions = [
    { question: "What is the capital of France?", options: ["1", "2", "Rome", "10"], correct: "Paris" },
    { question: "What is 2 + 2?", options: ["3", "4", "5", "6"], correct: "4" },
    { question: "What is the largest planet in our solar system?", options: ["Earth", "Mars", "Jupiter", "Saturn"], correct: "Jupiter" },
    // Add more questions as needed
];

function loadQuestions() {
    const container = document.getElementById('questionsContainer');
    questions.forEach((q, index) => {
        const questionDiv = document.createElement('div');
        questionDiv.classList.add('question');
        questionDiv.innerHTML = `
            <p>${q.question}</p>
            <div class="options">
                ${q.options.map((option, i) => `
                    <label>
                        <input type="radio" name="question${index}" value="${option}">
                        ${option}
                    </label>
                `).join('')}
            </div>
        `;
        container.appendChild(questionDiv);
    });
}

function submitQuiz() {
    const formData = new FormData(document.getElementById('quizForm'));
    const answers = { quizName: "Matrix Quiz" };
    let allAnswered = true;
    let correctCount = 0;

    // Check if all questions are answered
    questions.forEach((q, index) => {
        const answer = formData.get(`question${index}`);
        const questionElement = document.querySelector(`input[name="question${index}"]`).closest('.question');
        if (!answer) {
            allAnswered = false;
            questionElement.classList.add('error');
        } else {
            questionElement.classList.remove('error');
            const isCorrect = answer === q.correct ? "True" : "False";
            answers[`question${index + 1}`] = { answer: answer, correct: isCorrect, trueAnswer: q.correct };
            if (isCorrect === "True") {
                correctCount++;
            }
        }
    });

    // Check if all text inputs are filled
    const textInputs = ['input1', 'input2', 'input3'];
    textInputs.forEach(inputName => {
        const inputElement = document.getElementById(inputName);
        const inputValue = formData.get(inputName);
        if (!inputValue) {
            allAnswered = false;
            inputElement.classList.add('error');
            inputElement.style.backgroundColor = '#ffcccc'; // Set background color to red
            console.log(`Input ${inputName} is empty`); // Debugging log
        } else {
            inputElement.classList.remove('error');
            inputElement.style.backgroundColor = ''; // Reset background color
            answers[inputName] = inputValue;
        }
    });

    if (!allAnswered) {
        alert('Please answer all questions and fill in all text boxes.');
        return;
    }

    answers['timestamp'] = new Date().toLocaleString();

    // Calculate and display the percentage of correct answers
    const totalQuestions = questions.length;
    const percentageCorrect = ((correctCount / totalQuestions) * 100).toFixed(2);

    // Display correct answers and percentage in the results div
    let correctAnswers = "Correct Answers:<br>";
    questions.forEach((q, index) => {
        correctAnswers += `Q${index + 1}: ${q.correct}<br>`;
    });
    correctAnswers += `<br>You got ${percentageCorrect}% of the answers correct.`;

    document.getElementById('results').innerHTML = correctAnswers;

    const json = JSON.stringify(answers, null, 2);
    const xml = jsonToXml(answers);
    const timestamp = new Date().toLocaleString().replace(/[\/, :]/g, '');

    downloadFile(json, `matrix_${timestamp}.json`, 'application/json');
    downloadFile(xml, `matrix_${timestamp}.xml`, 'application/xml');

    // Reset the quiz
    resetQuiz();
}



function jsonToXml(json) {
    let xml = '<quiz>';
    for (const key in json) {
        if (json.hasOwnProperty(key)) {
            if (typeof json[key] === 'object') {
                xml += `<${key}>`;
                for (const subKey in json[key]) {
                    if (json[key].hasOwnProperty(subKey)) {
                        xml += `<${subKey}>${json[key][subKey]}</${subKey}>`;
                    }
                }
                xml += `</${key}>`;
            } else {
                xml += `<${key}>${json[key]}</${key}>`;
            }
        }
    }
    xml += '</quiz>';
    return xml;
}

function downloadFile(content, filename, contentType) {
    const blob = new Blob([content], { type: contentType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

window.onload = loadQuestions;

function resetQuiz() {
    // Clear radio button selections
    const radioButtons = document.querySelectorAll('input[type="radio"]');
    radioButtons.forEach(radio => {
        radio.checked = false;
    });

    // Clear text inputs
    const textInputs = document.querySelectorAll('input[type="text"]');
    textInputs.forEach(input => {
        input.value = '';
        input.classList.remove('error');
        input.style.backgroundColor = ''; // Reset background color
    });

    // Clear results
    document.getElementById('results').innerHTML = '';
}

    </script>
</body>
</html>

Hi there!

Put your code in to a live editor and post a link to it.

Hi @zaphod00101010

Try setting the margin-top property to 0 for the input elements.

Happy coding

Thanks for the replies,

hasanzaib1389 is the live editor on this site ?

Teller, i tried adding the margin-top:0px; to the the options and it stayed the same

.options {
    display: flex;
    flex-direction: column; /* Align items vertically */
    align-items: center; /* Center align the items horizontally */
margin-top:0px;
}
.options label {
    display: flex;
    align-items: left; /* Center align the label and input */
    margin-bottom: 5px;
    cursor: pointer;
margin-top:0px;
}
.options input[type="radio"] {
    margin-left: 20px; /* Space between the radio button and the label text */
	align-items: center;
width:100%;
margin-top:0px;
}


thanks

Try it on the input selector.

hi teller i tried that and it stayed the same

.text-input {
    margin-bottom: 20px; 
margin-top:0px;
	
}
.text-input label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #00FF00;
margin-top:0px;
}
.text-input input[type="text"] {
    width: 80%;
    padding: 10px;
    border: 1px solid #00FF00;
    border-radius: 5px;
    background-color: #000;
    color: #00FF00;
margin-top:0px;
}

![maatrix|617x435](upload://fuzrBjA2o3rYhNAfvz2CWp1OR6I.png)

if all the text is the same as in question 2 it looks ok ,its when the text varies it pushes the radio buttons out to the left. If i ialign to the left it lines up but im looking to get the radio buttons and text centered,

You can use Codepen. I

thanks hasanzaib1389, ive set up an acoount and just trying to get the code to work onit

hi this seems to work, i put a span into the javavscript code that generates the questions

.options {
    display: flex;
    flex-direction: column;
    align-items: center; /* Center align the items horizontally */
    width: 100%; /* Ensure the options take the full width */
}

.options label {
    display: flex;
    align-items: center; /* Center align the label and input vertically */
    margin-bottom: 5px;
    cursor: pointer;
    width: 100%; /* Ensure the label takes the full width */
    justify-content: center; /* Center align the label and input horizontally */
}

.options label span {
    display: inline-block;
    width: 200px; /* Set a fixed width for the label text */
    text-align: left; /* Align the text to the left within the span */
}

.options input[type="radio"] {
    margin-right: 10px; /* Space between the radio button and the label text */
}


and changed the css

.options {
display: flex;
flex-direction: column;
align-items: center; /* Center align the items horizontally /
width: 100%; /
Ensure the options take the full width */
}

.options label {
display: flex;
align-items: center; /* Center align the label and input vertically /
margin-bottom: 5px;
cursor: pointer;
width: 100%; /
Ensure the label takes the full width /
justify-content: center; /
Center align the label and input horizontally */
}

.options label span {
display: inline-block;
width: 200px; /* Set a fixed width for the label text /
text-align: left; /
Align the text to the left within the span */
}

.options input[type=“radio”] {
margin-right: 10px; /* Space between the radio button and the label text */
}