For example, I have this CSS script:
<style>
.header{
background:none:
color:#fff;
}
</style>
Then, I would like to change the header value to:
<style>
.header{
background-color:#fff:
color:#000;
}
</style>
The values are stored in database. What makes me confused is which should be the best to do that: Using PHP script or CSS or even javascript.
I want it changed based on the CSS value from my database which I can change again when I need it (by using PHP script). Perhaps this question is too general but, please give me some scripts which I can perform it well.
Thanks for any help.
asked Dec 24, 2014 at 11:53
5
first, change the extension of your file from (e.g.) style.css to style.php . Then add this to the first line of your css:
<?php
header('Content-Type: text/css');
?>
and after that you can define the value of your background as a variable and change it easily.
background: <?php echo $value; ?>
and in your php file:
<?php value = "#fff"; ?>
UPDATE:
<?php $value = "#fff"; ?>
Joe Kdw
2,2351 gold badge22 silver badges38 bronze badges
answered Dec 24, 2014 at 12:14
Majid SadrMajid Sadr
8337 silver badges17 bronze badges
2
For maintainability and flexibility reasons, I want to propose the frontend, not a backend solution (also because so far nobody proposed that).
I especially like the approach taken in the Grips library, where you can compile CSS template, passing in variables as an input (i.e. colors), and get the CSS to use. All of that can happen in the browser. And you can use Grips for HTML templating as well.
As I mentioned in the comment, this video is the best introduction to Grips.
Also note that if you want to use Grips in the backend, you can — but it’s a JS library, so it wouldn’t fit perfectly into your PHP solution.
answered Dec 24, 2014 at 12:06
kamituelkamituel
33.9k5 gold badges80 silver badges98 bronze badges
I think its same for both way.
If you want to use php then you will have to use inline css or style tag and its simple to.
Like
$color = (!dbValue?"defaule value":dbValue);
<style>
.header{
background-color:<?=$color?>:
color:#000;
}
</style>
answered Dec 24, 2014 at 11:58
Pratik BodaPratik Boda
3942 silver badges6 bronze badges
Make a php page in that write
$row = mysql_fetch_array(mysql_query('select * from table'));
<style>
.header{
background-color: <?php echo $row['bg_color_from_db']; ?> //change variable
color:<?php echo $row['color_from_db']; ?>; //change variable
}
</style>
answered Dec 24, 2014 at 12:00
Rana SoyabRana Soyab
8985 silver badges20 bronze badges
2
In order to achieve this you will need to use all three together, I am assuming you are using a LAMP set up on the back end. You will use PHP to first retrieve the values and store them, here is a good post to show this.
Link to Example on Stackoverflow
Once you have your values stored you will then need to create a file to change the DOM using JavaScript. Here is a good starting point produced by Mozilla Developers:
Mozilla JavaScript and CSS
The reason I suggest using JavaScript to achieve this is the ability to listen for events and change the client side in response. Hope this helps.
answered Dec 24, 2014 at 12:01
hudsond7hudsond7
6268 silver badges22 bronze badges
Import your database here In css or include db page;
$bg_color=$_row['column name'];
background-color:$bg_color;
And something like this you will be able to change your Background color using the value stored in database
marc_s
722k173 gold badges1320 silver badges1443 bronze badges
answered Dec 24, 2014 at 12:10
Amit VermaAmit Verma
40.3k20 gold badges92 silver badges112 bronze badges
I have a little question. Can I dynamically change (with php) content of the css style in this way?
<?php
header("Content-type: text/css; charset: UTF-8");
$color = "red;";
?>
header {
color:<?php print $color; ?>
}
?>
asked Oct 6, 2013 at 14:05
user2579395user2579395
771 gold badge3 silver badges10 bronze badges
7
Sure it’s possible, why not give a try?
Linking the php css in HTML:
<link rel="stylesheet" type="text/css" href="css/name-of-file.css.php">
and in your css.php file you put your code, but without the
<style type="text/css">
so it should look like this
<?php
header("Content-type: text/css; charset: UTF-8");
$color = "red;";
?>
header {
color:<?php print $color; ?>
}
answered Oct 6, 2013 at 14:12
StandardStandard
1,40016 silver badges34 bronze badges
4
It is better you use your javascript to change the style between php tags.
for example:
if($response){
echo "<script>
$('#matter_table').css('display', 'block');
</script>";
} else{
echo "<script>
$('#matter_table').css('display', 'none');
</script>";
}
answered Aug 18, 2015 at 9:52
You should try this
<?php
echo<<_CSS
<style>
body{
color:red;
}
</style>
_CSS;
?>
answered Oct 6, 2013 at 14:34
Например, у меня есть этот CSS script:
<style>
.header{
background:none:
color:#fff;
}
</style>
Затем я хотел бы изменить значение заголовка на:
<style>
.header{
background-color:#fff:
color:#000;
}
</style>
Значения хранятся в базе данных. Меня смущает то, что должно быть лучше всего: использование PHP скрипт или CSS или даже javascript.
Я хочу, чтобы он изменился на основе значения CSS из моей базы данных, которое я могу изменить снова, когда мне это нужно (используя PHP скрипт). Возможно, этот вопрос слишком общий, но, пожалуйста, дайте мне несколько сценариев, которые я могу выполнить.
Спасибо за любую помощь.
24 дек. 2014, в 12:55
Поделиться
Источник
6 ответов
сначала измените расширение своего файла с (например.) style.css на style.php. Затем добавьте это в первую строку вашего css:
<?php
header('Content-Type: text/css');
?>
после чего вы можете определить значение своего фона как переменной и легко изменить его.
background: <?php echo $value; ?>
и в вашем php файле:
<?php value = "#fff"; ?>
UPDATE:
<?php $value = "#fff"; ?>
Majid Sadr
24 дек. 2014, в 12:44
Поделиться
Для удобства и гибкости я хочу предложить интерфейс, а не бэкэнд-решение (также потому, что до сих пор никто не предлагал это).
Мне особенно нравится подход, сделанный в Grips library, где вы можете скомпилировать шаблон CSS, передавая переменные как входные данные (то есть цвета), и получить CSS для использования. Все это может произойти в браузере. Также вы можете использовать Grips для шаблонов HTML.
Как я уже упоминал в комментарии, это видео — лучшее введение в Grips.
Также обратите внимание, что если вы хотите использовать Grips в бэкэнд, вы можете — но это JS-библиотека, поэтому она не будет идеально вписываться в ваше решение PHP.
kamituel
24 дек. 2014, в 13:40
Поделиться
Импортируйте свою базу данных здесь. На странице css или include db;
$bg_color=$_row['column name'];
background-color:$bg_color;
И что-то вроде этого вы сможете изменить цвет фона, используя значение, хранящееся в базе данных
starkeen
24 дек. 2014, в 13:04
Поделиться
Создайте страницу php в этой записи
$row = mysql_fetch_array(mysql_query('select * from table'));
<style>
.header{
background-color: <?php echo $row['bg_color_from_db']; ?> //change variable
color:<?php echo $row['color_from_db']; ?>; //change variable
}
</style>
Rana Soyab
24 дек. 2014, в 12:54
Поделиться
Я думаю, что это одно и то же для обоих способов.
Если вы хотите использовать php, вам придется использовать встроенный CSS-код или тег стиля и его простое.
Как
$color = (!dbValue?"defaule value":dbValue);
<style>
.header{
background-color:<?=$color?>:
color:#000;
}
</style>
Pratik Boda
24 дек. 2014, в 12:24
Поделиться
Чтобы достичь этого, вам нужно будет использовать все три вместе, я предполагаю, что вы используете LAMP, настроенный на задней панели. Вы будете использовать PHP, чтобы сначала получить значения и сохранить их, вот хороший пост, чтобы показать это.
https://stackoverflow.com/questions/9083089/use-php-code-in-external-javascript-file
После сохранения ваших значений вам необходимо будет создать файл для изменения DOM с помощью JavaScript. Вот хорошая отправная точка, созданная разработчиками Mozilla:
Mozilla JavaScript и CSS
Причина, по которой я предлагаю использовать JavaScript для достижения этой цели, — это возможность прослушивать события и изменять клиентскую сторону в ответ. Надеюсь, это поможет.
hudsond7
24 дек. 2014, в 12:18
Поделиться
Ещё вопросы
- 0Невозможно отобразить полученное значение из базы данных в codeIgniter
- 0пытаясь получить данные между кварталом и годом
- 1литье и агрегирование по длине в пандах
- 0Переадресация .htaccess в index.html и index.php не работают вместе
- 0как добавить маршрутизацию с помощью angular-ui-router?
- 0как отобразить выбранные записи в порядке убывания по последнему идентификатору MySQL PHP
- 0Подтвержденная форма JQuery не отправляется
- 0изолировать объекты друг от друга, angularjs
- 1Как получить токен на предъявителя в консольном приложении .Net?
- 1Назначить переменную из текста
- 1Chainer — прогнозирование с использованием графического процессора
- 0Динамически читать значение поля ввода html: python
- 0проблема, связанная с методом POST и GET в HTML
- 1Изменить этот учебник для доступа к изображениям с SD-карты?
- 1получить исключение при вставке событий в календарь Android
- 0Эффективность std :: tuple и std :: map
- 0Доступ к значениям содержимого $ при создании темы Drupal
- 0Определить, находится ли 3d координата внутри усеченного конуса
- 1заполнение списка объектов в linq to sql
- 0Автозаполнение jQuery UI плагин с JSP и сервлетов не работает
- 1Доступ к USB-порту в C # [закрыт]
- 0Несколько ползунков на одной странице, привязав ползунок jquery к изображениям, загруженным в ajax
- 0Chrome Hard Reload с использованием JS
- 1Как устранить ошибки пути BindingExpression в выходных данных отладки, которые не влияют на приложение WPF?
- 1Как установить FEATURE_SECURE_PROCESSING в XMLReaderFactory?
- 0Карты Google не отображаются в IE / FF
- 0Добавить текст из HTML в XML
- 0Добавление активного класса для ссылки «Домой» JS
- 1Android SQLite запросы помечены как ошибка Android Studio
- 1vcalendar vs icalendar
- 1Загрузить файл на сервер Apache
- 1Как выполнить файл конфигурации flume с помощью Java-программы?
- 0Как найти объект JSON, содержащий объект или массив в Javascript?
- 0Компиляция программы на С ++ в Ubuntu
- 1Python — Сумма по уникальным атрибутам в списке атрибутов
- 1Можете ли вы заблокировать входящий трафик с помощью приложения для Android?
- 0Как остановить asp.net кодирование символов перед выводом в html?
- 1Почему я получаю случайные значения, когда значение инициализатора установлено на тензор?
- 0сравнивая два столбца из двух таблиц mysql, чтобы найти разные значения
- 1Является ли формат файла конфигурации DRBD стандартным?
- 1ListView является частью деятельности, а не деятельности?
- 1Как отладить код JavaScript, когда он загружен document.write?
- 1Поддерживается ли режим Wi-Fi Adhoc Mode в Android?
- 0Свести массив и сохранить индекс в качестве значения позиции
- 1Видео не отображается должным образом
- 1Сохранение ссылки на актерскую систему
- 0Невозможно создать таблицы в sqlalchemy postgresql
- 1Разница между C # dll, созданной на локальном компьютере, и сервером сборки TFS
- 0Как разместить элемент прямо под «абсолютным» div?
my head was spinning over this idea for a long time . and i though this is the right plce to ask for help ..
so what i want to do is make a really simple php file that make a search and replace in css files but the problem that i have is that a single css file can (as you all know ) have a 100 or more background tags and all i want to edit is one of them .. and what is some body added a line before or after … so search and replace for the whole section of the css file that i want to replace well be useless unless it is all the same ..
i really have a bad time explanning but i hope that you get the main idea ..
all i want is some guidelines in this .. help is really appreciated/
asked Aug 22, 2011 at 19:36
3
I wouldn’t suggest directly editing a linked CSS file through PHP (file_get_contents()) or something, but rather conditionally link different CSS files. Or perhaps, conditionally change what you need to change through CSS directly in HTML with PHP. For example, need to change background (for some reason) for different users, you would conditionally change the image source through PHP.
answered Aug 22, 2011 at 19:43
jn1kkjn1kk
4,9422 gold badges42 silver badges72 bronze badges
3
Why exactly do you want to do this? Maybe a CSS alternative like LESS is a viable option (it has support for variables etc)
answered Aug 22, 2011 at 19:42
RijkRijk
10.9k3 gold badges29 silver badges45 bronze badges
1
You can either use php to load a stylesheet.php that is dynamically generated or use javascript to «compile» it on the client side (like LessCss)
answered Aug 22, 2011 at 19:44
MiroMiro
8,1873 gold badges31 silver badges68 bronze badges
my head was spinning over this idea for a long time . and i though this is the right plce to ask for help ..
so what i want to do is make a really simple php file that make a search and replace in css files but the problem that i have is that a single css file can (as you all know ) have a 100 or more background tags and all i want to edit is one of them .. and what is some body added a line before or after … so search and replace for the whole section of the css file that i want to replace well be useless unless it is all the same ..
i really have a bad time explanning but i hope that you get the main idea ..
all i want is some guidelines in this .. help is really appreciated/
asked Aug 22, 2011 at 19:36
3
I wouldn’t suggest directly editing a linked CSS file through PHP (file_get_contents()) or something, but rather conditionally link different CSS files. Or perhaps, conditionally change what you need to change through CSS directly in HTML with PHP. For example, need to change background (for some reason) for different users, you would conditionally change the image source through PHP.
answered Aug 22, 2011 at 19:43
jn1kkjn1kk
4,9422 gold badges42 silver badges72 bronze badges
3
Why exactly do you want to do this? Maybe a CSS alternative like LESS is a viable option (it has support for variables etc)
answered Aug 22, 2011 at 19:42
RijkRijk
10.9k3 gold badges29 silver badges45 bronze badges
1
You can either use php to load a stylesheet.php that is dynamically generated or use javascript to «compile» it on the client side (like LessCss)
answered Aug 22, 2011 at 19:44
MiroMiro
8,1873 gold badges31 silver badges68 bronze badges
- Use CSS in a PHP-Only File
- Use CSS in a PHP+HTML File
- Use Inline CSS in PHP
echo
Statements
This article will teach you three methods that’ll help you use CSS styles in PHP.
The first method is via a PHP-only file, and the second is to embed PHP in an HTML+CSS file. Then the third method will use inline CSS in PHP echo
statements.
Use CSS in a PHP-Only File
A standard HTML file can embed CSS styles in the <head>
element or link to an external CSS file. By default, this CSS file will have the css
extension, but it can also have the php
extension.
This means you can write CSS code, save it as a PHP file and link it to your HTML. In this PHP file, you can do more than what you’ll do in a CSS file; you can write PHP code.
First, you can define a PHP code block with CSS property and values stored as variables. Then outside the PHP block, you can write normal CSS that’ll use the variables as values of CSS properties.
We’ve done that in the following; save it as styles.php
.
<?php
// The "header" is the most important part of
// this code. Without it, it will not work.
header("Content-type: text/css");
$font_family = 'Trebuchet MS, Verdana, Helvetica';
$font_size = '1.2em';
$background_color = '#000000';
$font_color = '#ffffff';
// Close the PHP code block.
?>
body {
background-color: <?php echo $background_color; ?>;
color: <?php echo $font_color; ?>;
font-size: <?php echo $font_size; ?>;
font-family: <?php echo $font_family; ?>;
}
Save the following HTML, and ensure you’ve linked styles.php
in the <link>
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Webpage using CSS styles generated with PHP</title>
<!-- Link styles.php as the CSS file -->
<link rel="stylesheet" type="text/css" href="styles.php">
</head>
<body>
<h1>Hello, We styled this page using CSS in a PHP file!</h1>
<h1>How cool is that?</h1>
</body>
</html>
Output:
Use CSS in a PHP+HTML File
HTML can use CSS via the <style>
tag or the <link>
tag, which can contain PHP in a dedicated PHP block. If the PHP code generates or manipulates HTML code, the linked CSS code can style the HTML.
For example, you can style the table using CSS if PHP pulls database records to make an HTML table. To show how to do this, create a database called my_website
in MySQL.
Next, create a site_users
table in my_website
using the following queries.
CREATE TABLE site_users (
user_id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
PRIMARY KEY (user_id)) ENGINE = InnoDB;
Insert data into the site_users
table.
INSERT INTO site_users (username, email) VALUES ('user_1', 'user_1@gmail.com');
INSERT INTO site_users (username, email) VALUES ('user_2', 'user_2@gmail.com');
INSERT INTO site_users (username, email) VALUES ('user_3', 'user_3@gmail.com');
Now, in the following, we have HTML, PHP, and CSS. The CSS is in the <head>
element; the PHP is in a PHP block within the HTML.
The PHP creates an HTML table using records from the site_users
table. When the PHP generates the table, the CSS will style it.
<!doctype html>
<head>
<meta charset="utf-8">
<title>Style MySQL table with CSS</title>
<style>
/* This CSS will style the table generated by PHP. */
table { border-collapse: collapse; width: 30em; font-size: 1.2em; }
table, th, td { border: 2px solid #1a1a1a; }
td,th { padding: 0.5em; }
/* Create a striped table. */
tr:nth-child(even) { background-color: #f2f2f2; }
/* General body styles. */
body { display: grid; justify-content: center; align-items: center; height: 100vh; }
</style>
</head>
<body>
<main>
<!--
We generated this table using PHP, and the CSS
style in the <style> tag will apply to it.
This is another way to use CSS in PHP.
-->
<?php
// Connect to the database. Change the connection
/// settings based on your environment.
$connect_to_mysql = new mysqli("localhost", "root", "", "my_website");
// Select the data from the site_users table.
$site_users = $connect_to_mysql->query("SELECT * FROM site_users")->fetch_all(MYSQLI_ASSOC);
// Get keys from the first row.
$table_header = array_keys(reset($site_users));
// Print the table.
echo "<table>";
// Print the table headers.
echo "<tr>";
foreach ($table_header as $value) {
echo "<th align='left'>" . $value . "</th>";
}
echo "</tr>";
// Print the table rows
foreach ($site_users as $row) {
echo "<tr>";
foreach ($row as $value) {
if (is_null($value)) {
echo "<td>NULL</td>";
} else {
echo "<td>" . $value . "</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
</main>
</body>
Output:
Use Inline CSS in PHP echo
Statements
PHP works well with HTML and has the echo
statement that can send HTML with inline CSS to the web browser. This is useful when debugging or sending large chunks of HTML to the web browser.
The following shows you how to use inline CSS with PHP echo
. We define the text and store three colors in the $colors_array
.
Then we use foreach
to loop through the $colors_array
, and we set the array element as the value of the inline CSS. When you run the code, the text appears three times with different colors.
<?php
$sample_text = "We generated this text color using inline CSS in PHP.";
$colors_array = ['red', 'green', 'blue'];
foreach ($colors_array as $value) {
// Use inline CSS with PHP echo.
echo "<p style='color: $value'>" . $sample_text . "</p>";
}
?>
Output:
DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!
When people are asked about features they would like to CSS, “variables” always seems to come up. Whether or not this is a good idea is still something I personally haven’t decided on, but I’d lean toward yes. Regardless, using PHP, it is trivially easy to use variables in CSS. This is certainly not a new trick, but I’ve never specifically covered it so I thought I ought to.
Style.php
Instead of using the .css file extension, use .php
<link rel='stylesheet' type='text/css' href='css/style.php' />
Content-type
At the top of your new style.php file set the Content-type back to CSS:
<?php
header("Content-type: text/css; charset: UTF-8");
?>
Set up variables
Now you can set up variables for whatever you like:
<?php
header("Content-type: text/css; charset: UTF-8");
$brandColor = "#990000";
$linkColor = "#555555";
$CDNURL = "http://cdn.blahblah.net";
?>
Use variables
Below all that PHP stuff, you can just commence regular CSS writing, only you can intermix some PHP to spit out those variables.
#header {
background: url("<?php echo $CDNURL; ?>/images/header-bg.png") no-repeat;
}
a {
color: <?php echo $linkColor; ?>;
}
...
ul#main-nav li a {
color: <?php echo $linkColor; ?>;
}
Extend the power / Other ideas
- While you are at it, might as well compress the CSS with PHP.
- Theoretically you could pull the user agent and attempt to do browser-specific CSS, but that is littered with problems and not recommended.
- Pull the date/time, and perhaps change some stuff on your site for the different seasons or time of day.
- Generate a random number, test the result, use it to set a random background image on your header.
Not working?
I did a totally static test page and it worked fine, then I tried this same technique within a WordPress site and no dice. The solution for me was to leave the file named style.css, and use .htaccess to parse it as PHP. Just make sure this code is in the .htaccess file (Apache servers only) at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.
<FilesMatch "^.*?style.*?$">
SetHandler php5-script
</FilesMatch>
Carlo DeAgazio wrote in to say this works for him in WordPress:
<?php
$absolute_path = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
$wp_load = $absolute_path[0] . 'wp-load.php';
require_once($wp_load);
/**
Do stuff like connect to WP database and grab user set values
*/
header('Content-type: text/css');
header('Cache-control: must-revalidate');
?>