Why can't I change the width of html buttons on class level in css?

Viewed 151

I want three buttons to each take up 33% of the assigned space. They are grouped in a class "numbers".

When I define the width for the button tags, that works fine, but when I do it for all buttons in the class that they belong to, nothing happens.

html:

<html>
<link rel="stylesheet" href="opmaak.css">
<body>
    <section class="numbers">
        <button type="button" value=1> 1</button>
        <button type="button" value=2> 2</button>
        <button type="button" value=3> 3</button><br>
    </section>
</body>
</html>

css when I do it on button level:

button {
    width: 33%;
}

css when I try it for all buttons of that class:

button.numbers {
    width:33%;
}

Could anyone point out why that is?

button.numbers {
    width: 33%;
}
<html>
<link rel="stylesheet" href="opmaak.css">
<body>
    <section class="numbers">
        <button type="button" value=1> 1</button>
        <button type="button" value=2> 2</button>
        <button type="button" value=3> 3</button><br>
    </section>
</body>
</html>

5 Answers

This is just an issue with the CSS selector:

button.numbers {
    width:33%;
}

Should be:

.numbers > button {
    width:33%;
}

Each button is a direct child of the .numbers class.

The original selector button.numbers would only select button elements that had a class of numbers (i.e. <button class="numbers" ...>).

Explanation

HTML's class attribute does not inherit to children HTML tags.

Actually, only the section tag has set its class="numbers".

Fix

So you have to mind that for using a fitting CSS selector.

Either use

.numbers > button

to only match direct (first order) children of button elements within elements of class number

or use

.numbers button

to match any children of button elements within elements of class number.

Of course there are many more possibilities to specify special selection needs.

it should be

.numbers button{
   width:33%;
 }
button.numbers {
    width:33%;
}

This css selector means apply styles to button tag which has class as numbers. It would work on this

 <button class="numbers" type="button" value=1> 1</button>

Your button tag don't have class.

The selector you have given specifies the with of each button element having the numbers class. Instead, you have wanted a selector that specifies each button children of an element having a numbers class:

.numbers > button {
    width: 33%;
}
<html>
<link rel="stylesheet" href="opmaak.css">
<body>
    <section class="numbers">
        <button type="button" value=1> 1</button>
        <button type="button" value=2> 2</button>
        <button type="button" value=3> 3</button><br>
    </section>
</body>
</html>

Related