Php dynamic css class

Dynamic CSS classes

The menu needs to be dynamically generated and each page needs to have a unique id or something at the top of the page. When you dynamically generate the menu, insert and if clause that will echo the active class if generated menu item is the same with current page.

I have not coded in php for some time now but i use to do something like this, in each page give a unique file name at the top. For example in the home page:

and then in the included file apply a logic like this:

 else if($file_name == "about.php") < //Your navigation for the about page >?> 

Alright so I will give you some tips. First, to know on wihch page of your website you are you can use in PHP a superglobal called $SERVER with this attribute : $_SERVER[‘REQUEST_URI’] .

By calling this, PHP is going to return the parts of the url after your domain.com. For example, if the current url was domain.com/home, echo will return only ‘/home’.

Then, you can place your logic about highlighting your links :

if($_SERVER['REQUEST_URI' == '/home') < //Add active class to the link HOME >. 

Arrabidas92 1075

You can try this one, but this is a Jquery, just put the CDN in your file.

$(document).ready(function() < if(window.location.href === "index.php") < $(".bd-nav").addClass("active-bgRed"); >else if(window.location.href === "about.php") < $(".bd-nav").addClass("active-bgBlue"); >else if(window.location.href === "contact.php") < $(".bd-nav").addClass("active-bgGreen"); >>); // CSS .active-bgRed < background-color: red; >.active-bgBlue < background-color: blue; >.active-bgGreen < background-color: green; >// JQuery CDN  

Myco Claro 465

More Answer

  • php dynamic css dropdown menu from sql db
  • css sprites for dynamic images using php
  • echo out multiple css classes for one div
  • How to adapt Twitter Bootstrap´s css classes to drupal menus?
  • Coding a dynamic PHP css based progress bar — maths percent issue
  • Get symfony2 client based dynamic CSS working somehow
  • How to reference CSS Classes via headLink in Zend_View?
  • How to reference CSS Classes via headLink in Zend_View?
  • foreach php for dynamic menu css
  • foreach php for dynamic menu css
  • PHP : Dynamic Variable Passed Between Classes
  • How to setTimeout for one of css classes of HTML element?
  • Creating dynamic methods inside classes
  • How to display a dynamic rating based on css and the value from PHP?
  • How to display a dynamic rating based on css and the value from PHP?
  • No CSS from include.php from level up directory
  • include header and footer from parent directory but not showing css
  • Use separate CSS for specific kiosk computer?
  • PHP Startup: Unable to load dynamic library, Library not loaded: libicui18n.52.dylib
  • custom css styles from (within — inside) wordpress dashboard
  • CSS — removing space between looped form buttons
  • Dynamic Dropdown with Link
  • create a filter searchbox to a checkbox list- dynamic response listing
  • CKeditor with multible dynamic textareas
  • chat div in ajax using css
  • Symfony2 — paths are wrong after ‘compiling’ SCSS —> CSS
  • Symfony2 — paths are wrong after ‘compiling’ SCSS —> CSS
  • PHP shell execution create dynamic command
  • dynamic ipBlock() ‘s in Widget
  • PHP Get Web page size including images, css & javascript
  • I have a php script with html div content. need to fetch php with html code including css
  • php read dynamic image file failed, need ideas
  • PHP Get Web page size including images, css & javascript
  • CakePHP FormHelper: how to ADD classes to default without replacing
  • Can’t rewrite URL because parameters are dynamic
  • Display a css style using the get url in php
  • CSS file filemtime without calling path twice
  • Dynamic Jquery Tabs based on Php foreach
  • dropzone.js — how can I post dynamic div id
  • PHP upload with dynamic url by action attribute.
  • PHP Dynamic Image Load
  • Validation in one place only — in form type classes
  • How to implement dynamic content types in CakePHP
  • php update dynamic sql rows through form
  • php update dynamic sql rows through form
  • Aligning search results with css
  • Add attribute checked for dynamic checkbox
  • unable to download dynamic library
  • Concatenation of a dynamic integer value in a php function
  • Dynamic HTML form input depending on SQL query results

More answer with same ag

  • How to read external rss file?
  • facebook php sdk — facebook login to my website success .. logout will log me out of facebook but not my website
  • how to save text file in to sql server database using php
  • why google recaptcha is not showing up?
  • Oscommerce Product Name and attribute to PayPal account
  • How to assign array value to textarea in smarty php
  • CKeditor displaying HTML tags in browser
  • How to get url the same as page title
  • php mailer with file upload
  • Autopost on facebook users wall
  • xml elements lost during processing with php
  • Admin login script with PHP and MySQL username and password is incorrect despite of correct input
  • Many-to-One — Symfony doesn’t generate proper ID-based relation
  • PHP: If it is correct update the database
  • Web API sent data without value
  • Images like a progress bar based on table value?
  • Looking for a class or something similar to create a log of while classes and functions a script calls
  • How to connect to sftp server via php
  • Real time data with Angular
  • modify to remove initial ul tag
  • find duplicate value in multidimensional array and combine their ID in comma separated with accordingly using PHP
  • Facebook SDK post photo likes
  • Ajax:Can’t get ajax to work properly
  • displaying records in search results with ajax
  • How to convert malformed database characters (ascii to utf-8)
  • Loading values into text area from database and then edit/update database with new values in PHP?
  • Fetching results from query and separating based on values — why won’t >< = symbols work correctly?
  • How to get RSS feeds off a PHP file or convert PHP to xml
  • Using phpseclib with a custom shell wrapper
  • Database retrieval system
  • Compilation failed : nothing to repeat at offset 19 (preg_match)
  • PHP — Loop through all links, remove content after last occurance
  • merrging two arrays at specific date if both date matched
  • Facebook comments on my website
  • Send HTML Form using SMTP
  • Wildly different encryption times with php and mcrypt?
  • Create JSON with same elements in PHP
  • php one function alias of another function — how to pass variables through
  • Order by Date this list
  • RegEx — extract words with prefix @ or #
  • Mysqli about security in a function
  • PHP cross Objective C iPhone
  • Extract the text from webpage
  • PHP Code for a large HTML Order Form to submit data to an email address
  • Sphinxclient search PHP
  • Is it possible ot send the $_FILES array to PHP using jQuery/AJAX?
  • PHP Memory Error(No File Name specified)
  • Any way to solve this loop on array problem i’m facing?
  • Mage::getSingleton(‘admin/session’)->getUser() is returning null
  • PrestaShop 1.4 — check if product has tag

Источник

Динамический CSS?

xCSS PHP Class

Я давно ждал этого момента, нет честно, где-то в подкорке я очень-очень хотел такой штуки чтобы было удобно писать на CSS без переписывания похожих стилей по два раза, без выыскивания нужных разделов в собственном коде, в общем хотелось чтобы на CSS можно было работать легко и просто, что-то я затянул…И так встречайте xCSS — php-класс для работы с динамическим CSS.
Заранее прошу прощения за вёрстку что-то у нас с Хабром в этот раз не заладилось (
Как я уже писал выше, xCSS — это класс для работы с динамическим CSS. Автор вдохновлённый идеей OO CSS и SASS (да-да, для Ruby уже есть такая штука) создал класс, который позволяет работать с CSS динамически: разработчику доступны переменные, классы, вложенные селекторы и прототипирование.
Что же даёт нам xCSS при первом рассмотрении? Во-первых, позволяет избежать путаницы в коде с помощью вложенных селекторов, во-вторых, позволяет избавиться от необходимости править всю таблицу стилей, если понадобилось поменять какие-то значения, в-третьих, сократить количество кода избавившись от повторяющихся правил, в-четвёртых, минимизировать код. Плюсы на лицо, теперь давайте познакомимся с xCSS поближе.

Переменные

Об этом новшестве мне хочется написать первым делом, все мы часто сталкивались с ситуацией когда нужно поменять цвет в макете, а всё уже почти готово, а поиск и замена не подходят потому что цвет нужно менять не везде, а только у определённых элементов или когда перед сдачей в продакшн необходимо вычистить все отладочные правила, а их много… Уф. Даже перечислять не хочется ситуаций когда требуется что-то быстро изменить, чтобы поменялось там где нужно, а там где не нужно — нет!
Теперь можно использовать переменные:

В примере я ставлю подчёркивание в конце переменных, это нужно для того чтобы необъявленные переменные не заменялись на переменные с общим префиксом. Проиллюстрирую выше сказанное: $newColor = #ffcc00 , а $newColorBg не объявлен, но используется в коде, в результате от $newColorBg останется #ffcc00Bg .
Строки в переменных можно не экранировать, они закрываются семиколоном (точкой с запятой).

Вложенные селекторы

Предположим есть у вас элемент товар и у него есть много вложенных элементов, которые требуют отдельного оформления: цена, описание, кнопка купить, номер модели и прочее. И конечно же теперь придётся писать сто раз подряд li.product тра-та-та… теперь всё проще:

li.poduct < a < color: $basicColor; >.price < color: $priceColor; font-size: 2em; >.buy < background-color: $attentionColor; >// … и т.д. И т.п. >
li.product a < color: $basicColor; >li.product .price < color: $priceColor; font-size: 2em; >li.product .buy < background-color: $attentionColor; >// … и т.д. И т.п.

Прототипирование

Возьмём три товара обладающих идентичным расположением элементов, но разными цветовыми схемами, например, обычный товар, бест-селлер и новинка. Сначала мы создадим прототип для обычного товара:

.product < self < min-width: 200px; min-height: 300px; >h1 < padding-bottom: 1em; color: $headersLight; >> .bestSeller extends .product < self < background-color: $productBestBg_; >h1 < color: $productBest_; >> .new extends .product < self < background-color: $productNewBg_; background-image: url($path/new_bg.png); >h1 < color: $productNew_; font-size: 1.2em; padding-bottom: 1.8em; >>

.new, .bestSeller, .product < min-width: 200px; min-height: 300px; >.new h1, .bestSeller h1, .product h1 < padding-bottom: 1em; color: $headersLight; >.new h1 < color: #00ffcc; font-size: 1.2em; padding-bottom: 1.8em; >.new < background-color: #0000cc; background-image: url(/storage/images/new_bg.png); >.bestSeller < background-color: #ff33cc; >.bestSeller h1

Как видите при использовании xCSS мы избежали дублирования имён классов (кроме имени прототипа) и при смене имени класса нам

PHP

  1. Кидаем файл xcss-class.php в библиотеку.
  2. В папке с xCSS-файлами создаём скрипт index.php и вставляем туда код:
$config = array(); $config['path_to_css_dir'] = '../'; // это рут для css и xcss директорий $config['xCSS_files'] = array ( 'styles/main.xcss' => 'generated/main.css', // имя файла xcss => сохранить как ); $config['master_file'] = true; // Использоват мастер-файл (файл в который будут включены все стили), по умолчанию true $config['master_filename'] = 'master.css'; // соответственно имя мастер-файла, по умолчанию 'master.css' $config['reset_files'] = array ( 'static/reset.css', // Стили сбрасывающие дефолтные настройки браузеров ); $config['hook_files'] = array ( 'static/hooks.css: screen', // Файлы для других медиа-типов (могу ошибаться) ); $config['construct_name'] = 'self'; // Имя элемента внутри себя, по умолчанию 'self' $config['compress'] = true; // Удалять лишние пробелы, по умолчанию false $config['debugmode'] = false; // Включает режим отладки, по умолчанию false $config['disable_xCSS'] = false; // Отключает xCSS, по умолчанию false $xCSS = new xCSS($config); $xCSS->compile();

От автора

Конечно я не использовал бы xCSS так как предлагает автор, а склеил бы все необходимые стили в один файл, сжал gzip’ом и закинул в кэш, а xCSS использовал бы только при разработке.
Спасибо за внимание!

Ссылки

Источник

Читайте также:  Gradle kotlin dsl script
Оцените статью