best way to create a class/data-attribute to hide content on certain devices

Hey, what would be the best method to create a class/data-attribute to hide content on certain devices? I'm using a data-attribute here. For the example codepen, i'm trying to hide a div with display: flex; on it whilst on a mobile viewport, whilst having it display otherwise. The problem is, since the data-attribute is using display: none to hide the div once it gets to mobile, the display: flex; overrides it and it doesn't disappear. I can't utilize !important since if i put it on the display: none, it makes the div disappear altogether, and if i put it on the display: flex; it gives the same result as the initial problem. Is there a more efficient way to do something like this so problems like this aren't encountered. Thanks in advance. https://codepen.io/deerCabin/pen/oNOQQXm?editors=1100
21 Replies
Shane
Shane2y ago
use a media query
ἔρως
ἔρως2y ago
unless you wanna do it from javascript, in which case you should stop and use a media query
snxxwyy
snxxwyyOP2y ago
alrighty, media query it is, thanks guys. is there no way to make it into a utility class at all though to prevent repeated code of hiding things haha?
ἔρως
ἔρως2y ago
you mean, like .hide-desktop?
snxxwyy
snxxwyyOP2y ago
yeah exactly that
ἔρως
ἔρως2y ago
the same way you do with anything else?
snxxwyy
snxxwyyOP2y ago
yeah, but in my example codepen i showed an issue with doing it the normal sort of way unless you mean put it in a media query like you said?
ἔρως
ἔρως2y ago
it's a slightly tiny bit more complicated than that, but not a lot but yes, everything should be in media queries @media (min-width: 50rem) { <-- by the way, don't use rems on media queries
snxxwyy
snxxwyyOP2y ago
oh, hm, what would you suggest instead?
ἔρως
ἔρως2y ago
pixels
snxxwyy
snxxwyyOP2y ago
would you mind explaining please? ah okay
ἔρως
ἔρως2y ago
you have to set the display value inside and outside the media query
snxxwyy
snxxwyyOP2y ago
would you mind showing an example please?
ἔρως
ἔρως2y ago
yes: check bootstrap
snxxwyy
snxxwyyOP2y ago
ohh bootstrap has it thanks
ἔρως
ἔρως2y ago
you're welcome
snxxwyy
snxxwyyOP2y ago
so something along the lines of this?
@media (max-width: 900px) {
[data-hidden-on="mobile"] {
display: none !important;
}
}

@media (min-width: 900px) {
[data-hidden-on="desktop"] {
display: none !important;
}
}
@media (max-width: 900px) {
[data-hidden-on="mobile"] {
display: none !important;
}
}

@media (min-width: 900px) {
[data-hidden-on="desktop"] {
display: none !important;
}
}
ἔρως
ἔρως2y ago
does it work?
snxxwyy
snxxwyyOP2y ago
indeed it does
ἔρως
ἔρως2y ago
are you happy with it?
snxxwyy
snxxwyyOP2y ago
yeah it seems to be the most efficient way i can think of

Did you find this page helpful?