I'm trying to find the most effective method for toggling display states on a webpage using a button while also being able to adjust based on screen size. For larger screens, I want to default to a horizontal layout with the option to switch to vertical. On smaller screens, the default should be vertical with no toggle available.
My current approach involves using cascading styles in the stylesheet, but I would prefer to avoid this as it requires careful order of styles.
HTML:
The default layout is set to layout--horiz
, with the layout
class used to override specific layouts with @media queries
.
<div id='layout' class='layout layout--horiz'>
<a href="#" id='btn'>Toggle</a>
<p>This</p>
<p>is</p>
<p>a</p>
<p>test</p>
</div>
CSS:
In the @media query
for small screens: hide the toggle button and apply the vert
styles directly to the layout
class to override layout--horiz
if necessary.
#btn {
display: block;
}
.layout--horiz p {
display: inline;
}
.layout--vert p {
display: block;
}
@media screen and (max-width: 600px) {
#btn {
display: none;
}
.layout p {
display: block;
}
}
JS:
To toggle between --horiz
and --vert
classes upon button click.
$('#btn').click(function() {
$('#layout').toggleClass('layout--vert layout--horiz');
});
This solution is functional, but I am open to suggestions for improvement.
Note: Feel free to experiment with this code on CodePen.