Адаптивный дизайн в php

Разработка адаптивного дизайна на PHP

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

Разработка адаптивного дизайна может быть выполнена на разных языках программирования, но здесь мы рассмотрим, как создать адаптивный дизайн на языке PHP.

Шаг 1: Определить разрешение экрана

Первым шагом в разработке адаптивного дизайна на PHP является определение разрешения экрана устройства, на котором будет отображаться сайт. Для этого можно использовать функцию PHP get_browser().

Эта функция позволяет определить разрешение экрана устройства и выполнить соответствующий код, в зависимости от этого.

Шаг 2: Использовать медиазапросы

Медиазапросы — это инструменты CSS, которые позволяют изменять стили элементов на основе критериев, таких как ширина экрана устройства. Это позволяет создавать адаптивный дизайн, который адаптируется к разрешению экрана.

@media screen and (max-width: 768px) < /* стили для мобильного устройства */ >@media screen and (min-width: 769px) and (max-width: 1024px) < /* стили для планшета */ >@media screen and (min-width: 1025px) < /* стили для десктопного устройства */ >

Шаг 3: Использовать фреймворки

Фреймворки — это готовые наборы инструментов для создания сайтов, которые включают в себя множество полезных функций, включая возможности для создания адаптивного дизайна. Некоторые из наиболее популярных фреймворков на PHP включают Bootstrap и Foundation.

Пример кода с использованием Bootstrap:

Здесь используются классы «col-sm-6» и «col-md-4», которые устанавливают ширину блоков содержимого в зависимости от ширины экрана устройства.

Наконец, после того, как адаптивный дизайн на PHP создан, необходимо проверить его работу на различных устройствах и браузерах. Существуют онлайн-инструменты, такие как BrowserStack, которые позволяют проверить работу сайта на разных устройствах и браузерах.

В заключение, разработка адаптивного дизайна на PHP может быть выполнена с помощью разных инструментов, включая функцию get_browser(), медиазапросы и фреймворки, такие как Bootstrap и Foundation. Важно помнить, что адаптивность сайта является ключевым фактором его популярности и успеха в наше время.

Похожие записи:

Источник

Адаптивность в создании сайтов

Адаптивность в создании сайта

Строки кода CSS, которые Я написал ниже, помогут Вам понять суть идеи адаптивности с помощью CSS.

Применение стилей в зависимости от разрешения экрана:

/*Стиль будет применяться при ширине экрана большей 1000 пикселей*/ @media screen and (min-width: 1000px) < body < color:red; >> /*Стиль будет применяться при ширине экрана меньшей 1600 пикселей*/ @media screen and (max-width: 1600) < body < color:red; >> /*Стиль будет применяться при ширине экрана большей 1000 пикселей и меньшей 1600 пикселей*/ @media screen and (min-width: 1000px) and (max-width: 1600px) < body < color:red; >> // Для высоты (height) аналогично

Применение стилей в зависимости от ориентации устройства (портретная, ландшафтная):

/*Стиль будет применяться при ландшафтном(альбомном) расположении экрана*/ @media screen and (orientation: landscape) < body < color:red; >> /*Стиль будет применяться при ширине портретном расположении экрана*/ @media screen and (orientation: portrait) < body < color:red; >>

Адаптация с помощью JavaScript

Еще один, простой способ сделать сайт адаптивным — это динамическое изменение размера сайта в зависимости от размера экрана.
Суть этого метода такова:
Имеем HTML страницу:

  Адаптация с помощью JavaScript     

Как видно из кода, у нас есть 3 блока «head_block — самый верхний блок(логотипы, верхнее меню и т.п.)», «main_content — блок с основным содержимым сайта», «footer — так называемый футер, или низ страницы».
Добавляем динамическое изменение с помощью JavaScript.

// Берем размер экрана пользователя var devWidth = $(window).width(); // Размеры блоков при загрузке страницы $(document).ready(function() < // Выставляем ширину для всех блоков равной ширине устройства $(".head_block").width(devWidth); $(".main_content").width(devWidth); $(".footer").width(devWidth); >); // Изменение размеров блоков при событии изменения размеров экрана $(window).resize(function() < $(".head_block").width(devWidth); $(".main_content").width(devWidth); $(".footer").width(devWidth); >); // Изменение размеров блоков при событии изменения ориентации дисплея window.addEventListener("orientationchange", function() < $(".head_block").width(devWidth); $(".main_content").width(devWidth); $(".footer").width(devWidth); >);
// Берем размер экрана пользователя var devWidth = $(window).width(); // Размеры блоков при загрузке страницы // Аналогично будут строится и реакции на другие события $(document).ready(function() < // Для экранов больше 600, но меньше 1000 пикселей if(devWidth>600 && devWidth <1000) < $(".head_block").width(700); $(".main_content").width(700); $(".footer").width(700); >// Для экранов больше 1000, но меньше 1600 пикселей else if(devWidth>1000 && devWidth <1600) < $(".head_block").width(1200); $(".main_content").width(1200); $(".footer").width(1200); >// Для остальных экранов, которые не подошли под предыдущие условия else < $(".head_block").width(1800); $(".main_content").width(1800); $(".footer").width(1800); >// Внимание! последнее условие также сработает на мобильные устройства // с небольшим разрешением (320, 480 пикселей), т.к. они не подходят // ни под одно наше условие >);

Помощь PHP в адаптации

В самом языке нету каких либо определенных функций, с помощью которых можно было адаптировать сайт под мобильные устройства.
Но! Язык PHP может помочь в адаптации сайта с помощью специальных плагинов, которые могут определять является ли устройство мобильным(планшет, телефон) или нет. А уже исходя из этого определения, можно подключать отдельные JavaScript скрипты или CSS стили, специально подготовленные для мобильных устройств.

Одним из таких плагинов является Mobile Detect. Это небольшой, простой в использовании плагин, который позволяет определить является ли устройство мобильным, какая операционная система используется на устройстве, а также какой браузер. Впринцепи, эти параметры можно «поймать» и самим, но т.к. мы на начале нашего пути, эти подробности опустим.
Самым простым способом использования плагина Mobile Detect это определение, является ли устройство мобильным или нет:

Более подробно о плагине Mobile Detect можно почитать на официальном сайте Mobile Detect

Это основы адаптации сайта под различные устройства. Но все же основным методом адаптации сайта является HTML — верстка.

Источник

Creating a Mobile-Friendly Website in PHP

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In the past few years, the number of mobile users (and mobile devices, of course) has been constantly increasing. This trend continues and according to a recent research, in 2015 there will be more mobile devices than people on Earth. Nowadays, people surf a lot using mobile technologies, which implies that the website owners need to make their websites mobile-friendly in order attract more visitors and web developers need to learn how to do that in order to make more money. Keep on reading to find out more about ways to create a mobile-friendly website, their advantages and how to apply them.

Solution 1 – Separate Websites for Desktop and Mobile

In this approach, we will actually create two websites – one for desktop users, and the other for mobile users. A complete separation of desktop and mobile websites allows you to have more control over the features i.e. it is easier to add a new feature for mobile users only or make some desktop features unavailable in the mobile website. Furthermore, recent research has shown that more than a half of the mobile users in the world have reasonably slow internet connections, which means that the mobile version must be much lighter that the desktop one in order to perform well – this is also easy to achieve using this approach. The disadvantage of this solution is that the changes to the website will have to be made twice, making the maintenance harder.

How to Create Separate Websites for Desktop and Mobile in PHP

Let’s assume that your website is already live. First, create a new subdomain for mobile users: e.g. m.yourdomain.com or mobile.yourdomain.com. Copy the main website’s files to that subdomain. Don’t duplicate the database.

At this moment, the mobile website is set up, but is still the same as the desktop one. It needs to be modified. The modification consists of two steps: 1) Remove unnecessary files and features and 2) Create a mobile-friendly design. During the first step, we make the mobile website lighter by removing unnecessary features, Javascript files, CSS, and making images smaller i.e. we are doing everything we can in order to make the website as fast as possible. The second step will produce new design. In most cases, a completely new design is made and is usually 320px wide.

Now, the mobile website is ready and customized, but the mobile users aren’t automatically redirected to the mobile version of the website. To solve this problem, we use a PHP MobileDetect class, which can detect whether a user is using a phone, a tablet or a desktop device to access a website. You can download this PHP class from here: https://code.google.com/p/php-mobile-detect/. Include the class in all PHP files and add the following code:

isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer'); $script_version = $detect->getScriptVersion(); $desktop = $_GET['desktop']; // If “Go to full website” link is clicked, redirect mobile user to main website if($desktop == 1) < $_SESSION['desktop'] = 1; header("Location:" . http://www.yourdomain.com); >// User is using a mobile phone, redirect him to mobile version of the website if($device_type == 'phone' && $desktop != 1 && $_SESSION['desktop'] != 1) < $url = current_url(); $mobile_url = str_replace('http://www','http://m',$url); // Redirect only if no form data submitted if (empty($_POST)) < header("Location:".$mobile_url); >> ?>

Where the current_url function is:

 $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") < $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; >else < $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; >return $pageURL; > ?>

This code detects if a user is visiting your website via a mobile phone and redirects him to the mobile version of the same URL he wants to visit. Also, this PHP code allows you to have a “Go to full site” button for mobile users – just put the following link: http://www.yourdomain.com/?desktop=1.

Solution 2 – Responsive Design

The second solution for creating a mobile-friendly website is responsive web design. As the name says, in this approach only the design is changed, i.e. CSS files. This is very good in terms of maintenance and SEO. Google recommends responsive design as the best solution when creating a mobile website. On the other hand, not being able to remove unnecessary files and scripts can have a great impact on your mobile website’s performance.

How to Create a Responsive Web Design

In responsive web design, we have different styles for different screen sizes. The screen sizes are targeted using media CSS queries, which are available in CSS3. The standard device widths for phones and tablets are the following:

/* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) < /* Styles */ >/* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) < /* Styles */ >/* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) < /* Styles */ >/* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) < /* Styles */ >/* iPads (landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) < /* Styles */ >/* iPads (portrait) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) < /* Styles */ >/* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) < /* Styles */ >/* Large screens ----------- */ @media only screen and (min-width : 1824px) < /* Styles */ >/* iPhone 4 ----------- */ @media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) < /* Styles */ >

You can, of course, remove some of the queries, depending on your needs. After deciding which sizes you will customize, you need to decide how the mobile device design should look, i.e. which elements will be removed and which ones will be resized. Then create CSS styles and apply them for each mobile view. Add the following meta tag in the head of your HTML code:

Keep in mind that the following meta tag may sometimes cause problems with iPad, so if the design doesn’t look good on an iPad, just remove this tag.

Conclusion

Creating a separate mobile website and responsive design are two approaches in creating a mobile-friendly website. There is no right or wrong approach. Use the one that best suits your needs.

Источник

Читайте также:  Python dunder methods documentation
Оцените статью