Hide for mobile css

How to Hide Elements in a Responsive Layout

To hide an element in a responsive layout, we need to use the CSS display property set to its «none» value along with the @media rule. The content of the second element having a «hidden-mobile» class will be hidden on devices smaller than 767px.

Please note that in order to get better results from examples, create an ‘index.html’ file in your local machine, and test the codes in your local browser by changing the page size.

Example of hiding an element on extra small devices:

html> html> head> meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> style> // show it on devices with max of 767 px and lower @media (max-width: 767px) < .hidden-mobile < display: none; > > style> head> body> h1>Hi h1> p>There is some text for example. p> p class="hidden-mobile">This text will be shown on large devices. p> p>There is some text for example. p> body> html>

In the below code, the media query uses @media (max-width: 576px) to apply the styles inside the block only if the device width is less than or equal to 576 pixels. The .element class has display: none inside this media query, which means that any element with the .element class will be hidden on extra small devices.

Читайте также:  Увеличение при наведении javascript

Note that the value of 576px is commonly used as the breakpoint for extra small devices, as it corresponds to the width of most smartphones in portrait orientation. However, this value can be adjusted as needed depending on the specific design requirements.

Example of hiding an element on small devices:

html> html> head> meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> style> /* Hide element on extra small devices */ @media (max-width: 576px) < .element < display: none; > > style> head> body> h1>Hi h1> p>There is some text for example. p> p class="element">This element will be hidden on extra small devices. p> p>There is some text for example. p> body> html>

Solutions with Bootstrap

In Bootstrap 3.4.1, we can use the «hidden-xs» class to hide an element on phones. So, in the next example, we demonstrate how a element will be hidden on extra small devices.

Example of hiding an element on extra small devices with Bootstrap:

html> html> head> meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> style> body < background: none; > style> head> body> h1>Hi h1> p>There is some text for example. p> strong class="hidden-xs">This text will be hidden on phones. strong> p>There is some text for example. p> body> html>

In Bootstrap 4, the hidden-* (also visible-*) class does not exist any more. To hide an element on some tiers or breakpoints, you need to use the d-* display classes.

Читайте также:  Установка spyder python windows

An extra small device (xs) is the default breakpoint if it is not overridden by a larger breakpoint. Thus, the -xs infix no more exists in Bootstrap 4.

In Bootstrap 4.3, to hide an element only on medium devices, use the «d-md-none» and «d-lg-block» classes.

Example of hiding an element on medium devices with Bootstrap:

html> html> head> meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> style> body < background: none; > style> head> body> h1>Hi h1> p>There is some text for example. p> p class="d-md-none d-lg-block">This text will be hidden on medium devices, but it will be shown on large devices. p> p>There is some text for example. p> body> html>

Источник

«Как показать или скрыть контент на сайте для разных разрешений экрана?»

как сделать шаблон адаптивным

Адаптивный дизайн – тот, который подстраивается под разные разрешения экрана при этом не теряя своей привлекательности. Это может производится как и засчёт адаптации каждого элемента сайта, так и банальным управлением отображения/скрытия контента на мобильных устройствах. Процесс создание адаптивного дизайна достаточно трудный, но скрыть или показать блоки сайта в зависимости от разрешения можно за несколько минут.

Как сделать адаптивную вёрстку?

Для того, чтобы сайт подстраивался под разные типы устройств, необходимо задать значения под все диапазоны экранов в таблице стилей CSS. Каждый шаблон состоит из блоков, у которых есть свой класс или идентификатор. Необходимо найти в таблице стилей нужный блок и прописать его поведение при различных экранных разрешениях. Возьмём, к примеру, фрагмент из таблицы стилей моего сайта. Блок w-container.

.w-containermargin-left:auto;margin-right:auto;max-width:940px> @media screen and (max-width:991px).w-containermax-width:728px>

Как видно из первой строчки, стандартная максимальная ширина для десктопного разрешения экрана составляет 940 пикселей. Из второй строчки легко заметить, что если максимальное разрешение экрана устройства в ширину не более 991 пикселя, блок будет растягиваться максимум на 728, что предотвратит разрушение структуры шаблона и контент будет всегда в зоне видимости.

И таким образом, нужно спроектировать и описать каждый блок шаблона сайта. Задача не из лёгких, согласитесь? Да и к тому же, очень индивидуальная. Однако, большинство шаблонов и фреймворков уже итак неплохо отображаются на мобильных телефонах, за мелкими исключениями. Поэтому, скрыть или показать некоторую информацию для определенных экранных разрешений будет достаточно, чтобы сайт более-менее сносно отображался на разных типах экранов.

Как скрыть часть информации от мобильных устройств?

как скрыть информацию для мобильных устройств

Как Вы уже поняли, в помощь нам приходит media screen в CSS, с помощью которого можно регулировать отображение структуры сайта в зависимости от разрешений экранов. Для начала, нам нужно заключить скрываемую информацию в дополнительный div-контейнер, назовём его hidemobile.

div class="hidemobile">информация, которую не надо отображать на мобильных телефонахdiv>

А после этого, добавить в style.css вашего сайта следующий фрагмент кода:

@media screen and (max-width: 600px) .hidemobile visibility: hidden; display: none; > >

В этом случае, если разрешение экрана устройства менее 600 пикселей, контент, заключенный в этот div, на нём не отобразится. Значение max-width Вы можете поменять на своё усмотрение.

Как сделать информацию видимой только на мобильных устройствах?

как показать информацию только для мобильных устройств

Возможно, у вас есть какое-то целевое предложение или контент, предназначенный только для владельцев смартфонов. Или же вы банально хотите показывать мобильным посетителям принципиально другое содержание страницы. В любом из этих случаев, рассмотрим способ отображения контента только на маленьких разрешениях экрана.

Порядок действий схожий с предыдущим пунктом. Обернем нужный контент в новый div.

div class="showmobile">информация, которую будет видно только на телефонахdiv>

А после добавим в style.css сайта этот фрагмент кода:

.showmobile display: none; > @media only screen and (min-device-width : 320px) and (max-device-width : 480px) .showmobile < display: inline; >>

Удачной вёрстки!

Как мы выяснили, при помощью несложных CSS-конструкций с применением media screen можно управлять отображением информации на странице. Также, предлагаю вам почитать каким должен быть продающий сайт и способы отправки HTML-писем.

Источник

How to Hide a div in Mobile but Show it on Desktop Or Vice Versa

How to Hide a div in Mobile but Show it on Desktop Or Vice Versa - xedricity

On this tutorial you learn how to hide any div tag on mobile but show it on desktop devices. Or vice versa if you want to show it on mobile but hide it on desktop. If you are pretty new to CSS then this tutorial will be your best bet. It’s pretty easy!

Hide div for mobile devices and show it on desktop or pc users. And hide a div for desktop or pc users but show it on mobile devices.

How to Hide a div in Mobile but Show it on Desktop Or Vice Versa

Ways on Hiding a DIV using CSS

Currently there are main two methods to hide a div tag using a CSS. Here’s a list for you to try on and see which works best in your scenario.

  • Using display:none – this method will literaly remove the div element or any element from the page. It doesn’t take space.
  • Using visibility:hidden – this method will just hide the element. It’s still there but its invisible from your eyes. What does that mean? It still takes space like if you are using this method on a paragraph and hide some words of it you will see blank spaces .

I am going to show you an example on how to perform both of these methods below. This is how you use it:

   .hide-1 .hide-2  

This is an axample on how to hide elements. You won't see texts after this. this word is totally hidden. It's like it wasn't there.

This is an axample on how to hide elements. You won't see texts after this. this word is totally hidden. It's there but its not visible.

Now, depends on what you want and how you want to use them. Both of these method will come handy. For showing div elements on mobile or desktop devices.

How to Hide div Element on Mobile but show it on desktop

Now, this is the real method you are looking for. Using the above mentioned CSS methods you can use these and apply on what we wanted like hiding the specific elements such as div’s on mobile but showing it on desktop.

     

This is an example only.

This text should be displayed on your PC or screen size larger than 600px. If yo use your mobile device or screen size smaller than 600px then you won't see this text.

All you have to do is make use of the @media screen tag which defines the size of the users screen. Most mobile device has screen less than 600px so we set the max-width of the screen to 600px only to limit the display of the CSS tag on those screen sizes only or below.

How to Hide div Element on Desktop but Show it on Mobile.

Now, we are going to reverse the process. We are now going to hide the div element for PC / Desktop users and display it on mobile users only. By now, you should have a pretty much good idea on what I am about to do.

      

This is how to hide element on PC but show it on Mobile.

This text should be displayed on your PC or screen size larger than 600px. If yo use your mobile device or screen size smaller than 600px then you won't see this text.

You see the difference? We set the screen size of the user to only 680px minimum width. And set to hide elements if the screen size is larger than 680px. But, show it on screen devices with less than 680px of screen size.

You can set the screen size to specific mobile device you want the element to be displayed of to be hidden. And, that is how you can hide an element or display it on any devices you want.

Источник

Оцените статью