Accordion using headings as buttons - change right alignment?

People,

Using this CSS:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

and this accordion:

<button onclick="myFunction('Demo1')" class="w3-btn w3-block w3-black w3-left-align">
<h4>Section h4</h4>
</button>
<div id="Demo1" class="w3-container w3-hide">
<p>Some text..</p>
  
<button onclick="myFunction('Demo2')" class="w3-btn w3-block w3-black w3-left-align">
<h5>Section h5</h5>
</button>
<div id="Demo2" class="w3-container w3-hide">
<p>Some text..</p>
  
<button onclick="myFunction('Demo3')" class="w3-btn w3-block w3-black w3-left-align">
<h6>Section h6</h6>
</button>
<div id="Demo3" class="w3-container w3-hide">
<p>Some text..</p>
  
<button onclick="myFunction('Demo4')" class="w3-btn w3-block w3-black w3-left-align">
<h7>Section h7</h7>
</button>
<div id="Demo4" class="w3-container w3-hide">
<p>Some text..</p>

and this script:

<script>
function myFunction(id) {
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else { 
    x.className = x.className.replace(" w3-show", "");
  }
}
</script>

I get this:


and for the different size headings, I want the left indentaion but how do I change the css to have an aligned right edge for all of the buttons?

Thanks!

Not sure using the w3schools css would be the best approach, but to answer your question, you’d need to add the following:

.w3-show { 
  display: flex !important;
  align-items: flex-end;
  flex-direction: column;
  margin-right: -16px; /* this is a magic number so buyer beware */
  width: 100%;
}
.w3-show > p { width: 100%;}

That gets you this:

Perfect! I will give that a shot . .

Have you a better option for what I am doing?

Thanks,
Phil.

You can’t nest block elements inside button elements as that is invalid. Only phrasing content is allowed which basically means inline elements such as span etc.

You don’t need the h4 inside the button anyway as you can style the text as you like. (Or alternatively don’t use the button but apply the styles and script to the h4 on its own.Or put the button inside the heading tag.)

1 Like

Instead of that magic number just remove the padding from the nested children. :slight_smile:

e.g.

.w3-container > .w3-container{
    padding-right: 0;
}

Assuming that they are all nested as all the closing divs are missing from the code supplied :wink:

There is no h7 in html. Headings only go up to h6 :wink:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.