Minify inline css code before its written to database, then unminify it when editing - wordpress

My theme has a custom css code block where I allow the site owner to add any custom css they need directly to the head section of the theme. This inserts whatever they've placed in this block into the wordpress database as a custom option insert.
I then retrieve this content into header.php and output it between an inline style tag like so...
<style type="text/css">
.test h1 {}
.testcss2, .somecss {}
</style>
This works perfectly fine, however, I would like to clean up and minify the markup when its written to the database. I suppose a regex is needed to do this? If so, what would that be?
The result I'm looking for, when the code is written into the page's markup is...
<style type="text/css">.test h1{}.testcss2,.somecss{}</style>
I'd also like to reverse the minified markup when its presented back to the user to edit in my theme options. In that view, I just want to reformat the minified css code so that each directive is back on its own line.

It depends what you want achieve by doing this. I agree with #thomasfedb that you will likely messup the style of most peoples CSS by doing this transformation and will likely cause more trouble than its worth.
It's my suggestion that you keep the data exactly as the user entered it, and then 'minify' it when you render it to the page.
This will not save you and storage in your database, and it will increase your CPU usage per page render, but it will save you the bandwidth of all the extra new-line characters.
Another option, presuming database storage is not much of a concern, is to store the data twice, once where the user edits, and once minified. Then simply minify and copy the user-editable field into the minified field whenever the user makes any changes.

I don't see any real reason to do this, a few newline charactors in a webpage isn't realy going to cost you very much page-weight.
Therefore my solution would be: don't.
Also, even if you reverse the minification, you might 'mess with the style' of some people, who like different css layouts.

Related

What is the best way to customize the design/skin of mediawiki?

I'm new to mediawiki and want to make my own skin for a mediawiki. For example I have a button (div.button-field > input) and I want to give it height: 100%. I know you can put it in a custom.css like
div.button-field > input {height: 100%;}
But if I do it for every element I want to customize the .css gets very long. The other thing, if I want only to customize a specific button which is nested like "div > div.container > form > div > div.button-field > input" and I add a div or remove a div, then it wont work anymore and I have to adjust the "path". So what would be the right way todo it? Or is the .css the best way todo it?
With kind regards
Oli
The answers depend on how much you want to change.
The first easiest path is to find an existing skin, see on MediaWiki.org.
You can configure some elements like the logo, the favicon or the sidebar, and you can change every text message of the interface.
Then, you can customise, as a logged-in administrator, the CSS rules by modifying the page MediaWiki:Common.css (example on English Wikipedia), or possibly MediaWiki:YourSkinName.css for skin-specific rules (for example MediaWiki:Vector.css to modify only the skin Vector; example on English Wikipedia).
You can also modify add JavaScript features by modifying MediaWiki:Common.js (example on English Wikipedia), or MediaWiki:YourSkinName.js for skin-specific rules (for example MediaWiki:Vector.js to modify only the skin Vector; the page does not exist on the English Wikipedia).
This kind of modification is recommended because it will be kept during MediaWiki updates, although minor adaptations could be needed on the long term.
If you want heavier changes, you can copy an existing skin, rename it, and change the PHP code, for instance by moving or deleting entire blocks. Prefer copying a well-supported skin like Vector or Monobook to be sure it is compatible with most MediaWiki extensions.
But it will take some or lot of work during MediaWiki updates (depends on the quantity of changes), and if you cannot do this work the risk is either you custom skin breaks or you will stay with an old MediaWiki version (which is not recommended for security reasons).
Also, if you choose this path, be warn not to break the structure expected by the VisualEditor if you want it continues to work.
There is a tutorial on MediaWiki.org to adapt the skinning from easiest ways to heaviest, see Manual:Skinning Part 1 and next pages.

My CSS is huge. Using ModX, can I split up a CSS into parts?

I have several large CSS files and making a change can sometimes take a few minutes just to find the right selector to change. I would like it if there was a nice ModX editor for CSS, but I haven't been able to find one. I am willing to settle for splitting up my files into parts, as long as my site still renders. Can I do that and how? If there is a nice editor (plugin?) instead, where can I find one?
I guess the real question is what kind of parts are acceptable for you. If you follow this question, you can begin the process of allowing ModX to manage your CSS. Once this happens, your options open considerably. Your CSS editing will then become easier and less time consuming depending on your level of expertise with ModX. This answer will be pretty simple, as it will show simply how to add a given selector as a resource. Other further development can be intuited from here, though.
CSS as a Resource
Once your CSS is being managed as a Resource (which takes about 15 minutes), you may utilize Templates, Template Variables, Chunks, Snippets and Plugins. Thisis actually pretty amazing, but setup can be a bit of a pain. You will basically be investing some time to save a lot of time in the future. The next logical step is split your Selectors accordingly, but you don't want to break what currently works. Having a fluid understanding of the getResources addon will be crucial to further development.
How to do it:
1. Create a new chunk
Click the Elements tab, and click "New Chunk". Name it "css-selector". Set the content to:
[[+pagetitle]] {[[+content]]}
It's as simple as that. Don't forget to click "Save"! This will let you set a Selector as a resource. It will use the title for the selector and content for the rules. You can forget about using those braces any more. Your new chunk will handle those from now on.
2. Adjusting your Template
Now, we just have to convince the template that it nows how to read parts, as well as not forget the whole. Open your CSS Stylesheet template (the one that says [[*content]] for its content). Adjust the code so that it has the following:
[[!getResources?
&parent=`[[*id]]`
&depth=`1`
&tpl=`css-selector`
&includeContent=`1`
&sortby=`menuindex`
&sortdir=`ASC`
&limit=`99`
]]
[[*content]]
Again, click "Save". Let me explain the Template real quick. If you have child, they'll get rendered first depending on their menu index. Further, it will render the contents of the document that are not children afterward. This will allow you to only make new resources for your most important selectors, while keeping the stuff that will never change in the main resource.
3. Create a new Template
This is so that your selectors don't do anything funny and just render the content. Create a new Template named "CSS Selector". Set its content to:
[[*content]]
4. Create a new Resource
Create a new Resource. Set the title to the selector for the css statement you want to manage. Then set the content to the rules without the braces. For instance, if your css statement is: div#header .logo {border:0;}, you'll set the title to div#header .logo and the content to border:0;. Set the resource alias to whatever you want. I use numbers for each one. Set the template to your new "CSS Selector". Important Now, set the Parent Document to your Stylesheet. Click Save.
5. Testing the Stylesheet
First, Right-click your new resource and choose "View Resource". This will just make sure that the statement was rendered correctly. It should simply say your rule in CSS format.
Next, Right-Click the Stylesheet resource and choose "View Resource". You should see the Selector at the top and all of the other rules below it.
Final Considerations
Observations
You'll notice that your child resources do not have to be changed to "CSS" for Document Type. Only the parent stylesheet has to be. This allows for some neat stuff as your expertise with ModX grows.
You can change the order of rules by simply changing the menu index of them.
The number of rules that can be done this way is based on the &limit variable in the getResources statement in your template. &limit applies to each stylesheet, so in this example you have 99 statements per stylesheet that may be separate resources.
A Note on Server Load
This will place load on the server as the number of resources goes up. For development, keep the "do not cache flag" (!) on your getResources statement. Once you are done, remove the exclamation mark and let it all be cached. This will save a ton of load.
Further Development
I added an isEnabled template variable to mine so I can turn on and off each rule as I pleased.
You may possibly begin to manage your CSS on the front-end utilizing FormIt.
Custom Manager Pages may even be a better option for you.
Further abstraction might allow you to create Groupings of statements for even further organization.

User generated custom css

Hey, anyone have any idea what the best way to allow users to save custom css would be? Specifically, there are about 4 color values that I would like to allow a user to choose and these colors would be used to create a custom theme for the user. I'm thinking save values in the database and then using dom:loaded with prototype to set the custom style values but I'm wondering if theres a faster way? Like dynamically creating css files or something?
and then using dom:loaded with prototype
Awww, don't do that! That won't work when JavaScript is turned off.
Approach 1: Static stylesheet, dynamic values in document head
For the sake of not having to work with a dynamically created style sheet, have a separate, static CSS file with all the definitions that won't change.
<link rel="stylesheet" href="styles/static.css" type="text/css">
<!-- Or whatever you name it -->
All the definitions that will change, you could put into the head of the HTML document, fetching the user-changeable values from a database.
<style type="text/css">
.classname { font-size: (fontsize); } <-- Insert dynamic value here
.classname { color: (color); } <-- Insert dynamic value here
....
<style>
that way, the majority of the CSS stays in static, cacheable files, while the dynamic part won't cause another HTTP request.
Approach 2: Dynamic stylesheet
If you have a lot of dynamically changing values, put the entire style sheet into a script file and output it, replacing placeholders with the values from the database.
The downside to this is that to force the browser to reload the style sheet on changes, you'll have to work with a version approach stylesheet.css?version=400 which is pretty complex to do, but can sometimes be more desirable than littering the head section with CSS.
You decide which approach suits your situation better. I find myself choosing the first one most often.
I would save the 4 values in the database and then create a css file from those values. You would want to make sure and cache the created css file for each user so you don't have to dynamically create it each page view.
Creating a custom css file adds another request the browser has to make so you would need to make sure your setting up the headers correctly to cache it. If the user does change their settings you would need do something to ensure the browser immediately stops cashing the old css file and loads the new file. One way to do this is to change the url of the css file.
Example:
/usercustom.css?version=(last saved date hash)
Instead I would use your first approach and create a JSON array that you inject into the page and then you use your javascript framework to load and use the array to style the page.
You could also store the color values in the cookie from the server and use and or write to them on the client.
I think that best way is to save it to Db, because you don't want to allow user to mess with your website. At least if some pages are public.
And I personally think that answers like "do it without JavaScript" is nothing but old school BS... Did they tried to turn of JavaScript today? I don't think so... And by this paragraph I don't mean that you have to do it using JavaScript. Do it in a way that suits your needs 🤔
Wish you nice Day

Preferred method for linking to stylesheets from a UserControl?

We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.
So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think.
Does anyone have any preferred methods, and if so, what and why?
I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.
It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag & drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.
This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.
Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it.
When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.
What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.
I could use #import I guess but I think link tags are preferred, correct?
It sounds like you're rolling your own theme engine... why not use ASP.NET Themes?
If you're determined to do it yourself, here's some code from the CssFriendly project that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed.
string filePath = page.ClientScript.GetWebResourceUrl(type, css);
// if filePath is not empty, embedded CSS exists -- register it
if (!String.IsNullOrEmpty(filePath))
{
if (!Helpers.HeadContainsLinkHref(page, filePath))
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(filePath);
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}
}
I think what you're supposed to do is use Page.RegisterScriptBlock to register your script blocks. Best-case you shouldn't have them inline in your ascx inside script blocks. This isn't always possible, but theoretically it's the best way.
Ideally your styles should be separate from your markup as well. Your controls can have classes and IDs, but your style is based on your application and not your controls. Controls can theoretically be used in other applications where you might want a different style.
It depends on how big your app is, and whether or not it's dependent on Themes elsewhere, IMHO.
If you're using a .skin file, or if the majority of the app is also plugged into the theme, you might as well go with the theme.
But if it's just a few styles you need, you're better off to set the stylesheet manually, keep your css file external (inline styles are a PITA and defeat one of the core purposes of css).
In either case, don't forget to set the CssClass attribute on your controls.
To be proper I would have an import.css file - structure the naming of the classes to follow your controls, and import the styles within the header of the document.
If you have a module called "30DayPricingCalc" then you could name the classes/id's:
30DayPricingCalc.css
.30daypricingcalc_main_content
{
...
}
Also if you haven't I would setup a list of generic reusable styles to save you room. Since elements will allow multiple classes per object.
Also, link tags matter a lot less now than they used to. we're well past support for IE5 generation browsers and IE6 supports the #import tag.
Cheers!

How can I modify a CSS file programmatically?

I have a legacy application that I needed to implement a configuration page for to change text colors, fonts, etc.
This applications output is also replicated with a PHP web application, where the fonts, colors, etc. are configured in a style sheet.
I've not worked with CSS previously.
Is there a programatic way to modify the CSS and save it without resorting to string parsing or regex?
The application is VB6, but I could write a .net tool that would do the css manipulation if that was the only way.
You don't need to edit the existing one. You could have a new one that overrides the other -- you include this one after the other in your HTML. That's what the "Cascading" means.
It looks like someone's already done a VB.NET CSS parser which is F/OSS, so you could probably adapt it to your needs if you're comfortable with the license.
http://vbcssparser.sourceforge.net/
One hack is to create a PHP script that all output is passed through, which then replaces certain parts of CSS with configurable alternatives. If you use .htaccess you can make all output go through the script.
the best way i can think of solving this problem is creating an application that will get some values ( through the URL query ) and generate the appropriate css output based on a css templates
Check this out, it uses ASP.NET and C#.
In my work with the IE control (shadocvw.dll), it has an interesting ability to let you easily manage the CSS of a page and show the effects of modified CSS on a page in realtime. I've never dealt with the details of such implementations myself, but I recommend that as a possible solution worth looking at. Seeing as pretty much everyone is on IE 6 or later nowadays, you can skip the explanations about handling those who only have IE 5,4,3 or 2 installed.
Maybe the problem's solution, which is most simple for the programmer and a user is to edit css via html form, maybe. I suppose, to create css-file, which would be "default" or "standart" for this application, and just to read it, for example, by perl script, edit in html and to write it down. Here is just the simple example.
In css-file we have string like:
border-color: #008a77;
we have to to read this string, split it up, and send to a file, which will write it down. Get something like this in Perl:
tr/ / /s;
($vari, $value) = split(/:/, _$);
# # While you read file, you can just at the time to put this into html form
echo($vari.":<input type = text name = ".$vari." value = ".$value.">");
And here it is, you've got just simple html-form-data, you just shoul overwrite your css-file with new data like this:
...
print $vari[i].": ".$value.";\n";
...
and voila - you've got programmatical way of changing css. Ofcourse, you have to make it more universal, and more close to your particular problem.
Depending on how technically oriented your CSS editors are going to be, you could do it very simply by loading the whole thing up into a TextEdit field to let them edit it - then write it back to the file.
Parsing and creating an interface for all the possibilities of CSS would be an astronomical pain. :-)

Resources