Hide/Show Text Using CSS for Special Mobile Conditions

It always amazes me how flexible and accommodating CSS can be. There are things (like animations or screen size detection) that would have to be handled by many lines of javascript. That is not the case anymore.

In my mobile app, I ran into a situation where the graphs I was displaying were a bit undersized, but only on mobile devices. I would need to send a message to the users that the graphs look better in landscape mode, but I didn’t want he message to show up laptops or desktops with wider screens. So I used the CSS below.

.portWarn {
	display:none;
}

@media only screen and (max-device-width:500px)  and (min-device-width:320px) and  (orientation:portrait)

{

	.portWarn {
		display: block;
		color: #ff0000;
		font-size: .5em;
	}
}
@media only screen and (max-device-width:500px)  and (min-device-width:320px) and  (orientation:landscape){
	.portWarn {
		display: none;
	}
}

I created a class called .portWarn which is initially not displayed. Then if the device has a width of less than 500 pixels, it will display the message if it detects the device in portrait mode. Just remember, many newer devices have a display significantly greater than what your browser will detect (due to iOS Retina display), but the width will still be under 500 for most phones). Turning the phone sideways will make the graph larger and hide the message.

Of course I will make use of this suggestion on this page.  If you see this text, the image below may be too small.   Turn your device to landscape mode (sidewise)  to see it better!

Leave Comment

Your email address will not be published. Required fields are marked *