1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Concise CSS Tips

Discussion in 'HTML & Website Design' started by Web_Dev_Chris, Jun 18, 2019.

  1. #1
    What are some good coding practices to keep CSS code concise so that CSS code is effective and saving you time.

    Could you share tips that you have picked up on the way and lessons learned?

    I have picked up a few things along to way.
    • Using styles for things that require specific formatting on large websites as opposed to targeting elements individually which will produce long repeated code.
    • Grouping elements that are in the same section to save typing same properties over and over again.
    For example:
    #about-us{
    
    }
    
    /*Rather than*/
    
    #about us .title{
       text-align:center;
       letter-spacing: 1px;
       line-height: 145%;
    }
    
    #about-us .text{
       text-align:center;
       letter-spacing: 1px;
       line-height: 145%;
    }
    
    /* REPEATED STYLES LIKE THIS*/
    
    #about us .title,
    #about-us .text {
       text-align:center;
       letter-spacing: 1px;
       line-height: 145%;
    }
    
    Code (CSS):


    Thanks in advance!

    Regards,
    Chris
     
    Solved! View solution.
    Web_Dev_Chris, Jun 18, 2019 IP
  2. Gary-SC

    Gary-SC Member

    Messages:
    101
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    33
    #2
    It's one of a few good practices. "Do not repeat yourself" is a principle I'm still learning to practice better.
     
    Last edited: Jun 18, 2019
    Gary-SC, Jun 18, 2019 IP
  3. #3
    One thing to remember is that if you're given the choice between making bloated markup and bloated CSS, bloat the CSS. This is because if you're using a monolithic stylesheet (one single .css file per media target) it pre-caches the appearance of subpages, and caches the appearance should the same page be revisited.

    As a rule of thumb, dynamically generated HTML is not cached. New HTML pages are obviously not in the cache on first visit, but CSS can/is cached in most cases. Loading ALL the style up-front makes on-site navigation faster since all that has to be sent is the markup. To that end, the less markup you use, the better.

    ... and why the "target each element directly with classes" rubbish is exactly that, rubbish. Slopping classes onto everything is halfwitted, shortsighted, and utter/complete trash when we have selectors. Any claims of being "faster" at the render stage are 100% BS compared to making the parser work harder at even having something to render, and the waste of bandwidth.

    Again why -- on top of failing to even bother paying attention to the past 20 years of progress -- doing something like class="text-red text-center text-shadow box-shadow col-4-s col-6-m col-8-l" is mentally enfeebled BS created by people unqualified to write a single blasted line of HTML or CSS, much less be telling others how to do so!

    Learning the ins and outs of using the condensed properties is something I consider important. Sometimes you can end up with more code that's clearer/easier to maintain, that's worth the extra bandwidth as a result.

    Take changing the font-size. Since the "metricless" line-height is a bald faced LIE in terms of inheritance, you change the font-size you REALLY should be re-declaring the line-height... if your font stack is small enough, it's as many characters to just say the whole thing.

    Hence where you might say:

    
    font-size:2em;
    font-weight:bold;
    line-height:1.5em;
    
    Code (markup):
    it's often faster and less code to just:

    
    font:bold 2em/1.5em arial,helvetica,sans-serif;
    
    Code (markup):
    Whilst it's only 6 less bytes, and if you aren't setting the font-weight/style it might be even more, it's also more clear what exactly is being set. Remember, concise does not mean "as small as possible" as it should / must include CLARITY... and really if you want to change all elements using that font stack is ^H (replace) really that hard to use? One of those things that makes me think SCSS is trash, it's like these clowns can't figure out search and replace!

    Condensed properties can be even more useful with something like borders. Let's say you want a black border all around, but 0.25em on top, 0.5em at the sides, and 1 em at the bottom. This gets pretty damned obtuse really quick:

    
    border-top:0.25em solid #000;
    border-right:0.5em solid #000;
    border-bottom:1em solid #000;
    border-left:0.5em solid #000;
    
    Code (markup):
    But that can actually be stated using two different condensed properties as:

    
    border:solid #000;
    border-width:0.25em 0.5em 1em;
    
    Code (markup):
    Pretty slick. Learning the order of parameters on border/padding/margins is also important. Sometimes even if it's already set, such as:

    
    div { padding:1em; }
    
    Code (markup):
    It's faster and clearer to say:

    
    .special {
      padding:1em 1em 0 0.5em;
    }
    
    Code (markup):
    Than it is to say:

    
    .special {
      padding-bottom:0;
      padding-left:0.5em;
    }
    
    Code (markup):
    Since you then know exactly what the values on all sides are right then and there.

    One of the biggest flubs I see all the blasted time is people not realizing that pseudo-selectors, pseudo-states, and psuedo-elements all inherit off the parent tag. It's stupid how often you'll see:

    
    a:link {
    	color:#000;
    	text-decoration:none;
    }
    
    a:visited {
    	color:#000;
    	text-decoration:none;
    }
    
    a:active {
    	color:#00F;
    	text-decoration:none;
    }
    
    a:focus {
    	color:#00F;
    	text-decoration:none;
    }
    
    a:hover {
    	color:#00F;
    	text-decoration:none;
    }
    
    Code (markup):
    Even -- or perhaps especially -- in "frameworks" written by ALLEGED "experts"... doing the job of:

    
    a {
    	color:#000;
    	text-decoration:none;
    }
    
    a:active,
    a:focus,
    a:hover,
    	color:#00F;
    }
    
    Code (markup):
    It's so simple, but people make it hard, seemingly on purpose.

    One big thing I tell people to watch out for is the difference between minimalism and byte obsession. Do NOT be obsessed over every last single byte you can save if it compromises legibility, clarity, and sustainability. It's VERY easy to make CSS tiny, but don't go so far that you make it harder to maintain or introduce extra wasteful steps to the process.

    Again, "false simplicity" is a very easy trap to fall into. Like anything else, you can take it too far. There's a reason I wouldn't waste my time minifying HTML or CSS. If minification of those is showing any measurable benefit, there is likely something horrifyingly WRONG with either one... such as using 100k of HTML to do 16k's job, or 500k of CSS to do 32k's job... which are actually things that happen. See bootstrap.
     
    deathshadow, Jun 21, 2019 IP
  4. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #4
    Wow a short hand property for font! I had no idea. I’m aware of all the other ones like margin, padding and I’m sure there more that would come to memory when coding.
     
    Web_Dev_Chris, Jun 21, 2019 IP
  5. pxgfx

    pxgfx Well-Known Member

    Messages:
    93
    Likes Received:
    24
    Best Answers:
    0
    Trophy Points:
    100
    #5
    @deathshadow what method do you use (or you think is the best) to clear floats? What's your opinion on flexbox and (the new) css grid? Can I use flexbox with progressive enhancement? ... like designing the basic layout first with "float and clear" methods.

    CSS grid is "layout-first" so I think you're against that?

    I'm just getting back to coding and I think I've forgotten so much. I learned the basics of flexbox before when it was still new(er) but I can barely remember now how it all works.
     
    pxgfx, Jun 21, 2019 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #6
    Depends on what you mean by clear. If a sibling element, well 'clear:' of course.

    If you mean CONTAINING floats, then I will typically use overflow:hidden on the parent. In cases where the overflow is undesirable, width:100% and float on the parent container does the trick.

    I do not advocate or use clearing DIV, clearing BR, or any other such nonsense that really hasn't been needed since 2003.

    It's easier with flex actually. You just change the flex rules. The grid layout module makes it even simpler in fact. In either case that you can just change display:grid to display:static and boom, your columns disappear entirely? Perfect for that final narrowest media query if you're working sensibly from legacy desktop first down to mobile. I've said it a few places, I consider "mobile first" utterly back-assward since mobile is what we CAN target with media queries, legacy desktop we can't... so start with what we can't target, then apply style over it. It just makes sense.

    In what way is it "layout first"? The "CSS3 Grid layout module" may be painfully unfortunately named, but it's not 'layout first' in any sense nor does it really need markup significantly different from flex or floats? If anything it needs less markup than floats since you don't need extra containers for any of the negative margin trickery.

    The thing I think most people screw up with it is that it has not one blasted thing to do with the "grid" nonsense most of the PSD jockeys and bootcrap halfwits consider it to be. Whilst it can be used for that, that's not really what it's for. I've always considered that "division of 12" idiocy to be a perfect example of people who THINK they are designers flapping their yap about things they don't understand.

    I mean, a grid compatible markup where you need / want defined containers for a simple page has no reason to vary much from:

    
    </head><body>
    
    <input type="checkbox" id="toggle_dayNight" hidden>
    
    <div id="top">
    	<h1><a href="/">Site title</a></h1>
    	<input type="checkbox" id="toggle_mainMenu" hidden>
    	<label for="toggle_mainMenu"></label>
    	<ul id="mainMenu">
    		<li><a href="/">Home</a></li>
    		<li><a href="#">News</a></li>
    		<li><a href="#">Articles</a></li>
    		<li><a href="#">Tutorials</a></li>
    		<li><a href="#">Links</a></li>
    		<li class="alternate"><a href="#contact">Contact Us</a></li>
    		<li class="alternate"><a href="#search">Search</a></li>
    	</ul>
    <!-- #top --></div>
    
    <div id="content">
    	<h2>Start main content</h2>
    	<p>
    		Main content flow text here
    	</p>
    <!-- #content --></div>
    
    <div id="firstExtras">
    	<div>
    		<h2>Another subsection</h2>
    		<p>
    			Subsection content here
    		</p>
    	</div>
    	<div>
    		<h2>Another subsection</h2>
    		<p>
    			Subsection content here
    		</p>
    	</div>
    <!-- #firstExtras --></div>
    
    <div id="secondExtras">
    	<div id="advertisement">
    		<h2>Advertisement</h2>
    		Advert here
    	</div>
    	<div>
    		<h2>Another subsection</h2>
    		<p>
    			Subsection content here
    		</p>
    	</div>
    <!-- #secondExtras --></div>
    
    <div id="footer">
    	<hr>
    	Disclaimer Here
    <!-- #footer --></div>
    
    <form action="contact" id="contact" method="post" class="modal">
    	<a href="#"></a>
    	<div>
    		<a href="#"></a>
    		<h2>Contact Me</h2>
    		<fieldset>
    			<label for="mail_name">Your Name:</label>
    			<input
    				type="text"
    				id="mail_name"
    				name="mail_name"
    				required
    			><br>
    			<label for="mail_eMail">E-Mail Address:</label>
    			<input
    				type="email"
    				id="mail_eMail"
    				name="mail_eMail"
    				required
    			><br>
    			<label for="mail_eMailDupe">Confirm E-Mail:</label>
    			<input
    				type="email"
    				id="mail_eMailDupe"
    				name="mail_eMailDupe"
    				required
    			><br>
    			<label for="email_subject">Subject:</label>
    			<input
    				id="mail_subject"
    				name="mail_subject"
    				type="text"
    				required
    			>
    			<div>
    				<label for="mail_mailText">Message Body:</label>
    				<textarea
    					id="mail_mailText"
    					name="mail_mailText"
    					cols="44"
    					rows="4"
    					required
    				></textarea>
    			</div>
    		</fieldset>
    		<div class="submitsAndHiddens">
    			<button>Send Mail</button>
    			<input
    				type="hidden"
    				name="mailHash"
    				value=""
    			>
    		<!-- .submitsAndHiddens --></div>
    	</div>
    </form>
    
    <form action="search" id="search" method="get" class="modal">
    	<div>
    		<a href="#"></a>
    		<h2>Search</h2>
    		<fieldset>
    			<label for="search_term">Terms to look for:</label><br>
    			<input type="text" id="search_term" name="q" size="48">
    		</fieldset>
    		<div class="submitsAndHiddens">
    			<button>Go</button>
    			<input type="hidden" name="searchHash" value="">
    		</div>
    	</div>
    </form>
    
    </body></html>
    
    Code (markup):
    That's not really any different from the markup for a float based layout, and it's entirely capable of 1, 2, and 3 column layouts in any order, with the search and contact forms being modal dialogs and the menu able to "hamburger" or not, all without the need for a single line of JavaScript. I might consider adding one or two extra DIV for fixing the dual scrollbar issue of the modals when the screen is really tiny, and a few other corner case fixes, but for the most part using flex, grids, or even floats there's little if any difference in the markup... meaning it's certainly NOT "layout first" by any stretch of the imagination.

    So I'm really not sure where you got the idea that it was.

    I'm actually in the middle of a rewrite of one of my personal pages during some downtime, that uses, well... damned near that same markup, just with flex and not grid as I'm not QUITE ready to tell IE11 users to kiss my grits.
     
    deathshadow, Jun 21, 2019 IP
  7. pxgfx

    pxgfx Well-Known Member

    Messages:
    93
    Likes Received:
    24
    Best Answers:
    0
    Trophy Points:
    100
    #7
    Thanks! I didn't get the second trick tho: width:100% and float on the parent?

    That's a handy trick for sure! I actually find it harder to do mobile first lol, and I'm with you on targeting legacy desk first using progressive enhancement.

    What was that trick again for targeting CSS3 only browsers? Are you still using it?

    If you would be so kind, can you update the template.html and screen.css in your for_others dir, please? TIA!

    I used to be one of those PSD jockeys lol

    Now that you explained it, it sure is unfortunately named tsk ... I got the idea from this article:

    https://medium.com/youstart-labs/beginners-guide-to-choose-between-css-grid-and-flexbox-783005dd2412

    The way he explained it tho ...

    I wonder how many still use IE11. I know Windows 10 still comes with IE11 preinstalled.
     
    pxgfx, Jun 24, 2019 IP
  8. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #8
    Floats will wrap floats. If a float is 100% of the parent width, other floats can't fit next to it. So by setting width:100%; float:left; you'll actually prevent child floats from overflowing the parent. Handy trick when overflow:hidden chops off things like box-shadow when you don't want it to. Display:table-cell can do the same thing as well in some cases, as will both display:flex and display:grid.

    There are actually a LOT of tricks for float wrapping.

    Might sound weird, but a lot of times you are best off combining all three techniques. It's best not to treat any one of them as a complete replacement, as they often complement each-other well. That's a problem we see in web development a lot is that certain layout techniques end up being learned, and then used for everything regardless of if it's the right tool or not. Literally the old joke about the man with a hammer; suddenly everything looks like nails.

    When'if I need to target legacy browsers, I still use it. Since IE9/newer all support media queries, the easiest way to target CSS3 browsers is:

    @media (min-width:1px) {

    It's a sneaky trick, but it works. Another one I've been using lately:

    @supports (-webkit-appearance:none) {

    Is good if you're trying to use background-clip (which is useful for gradient text), which of course no version of IE supports. If you're layering generated content to add text-shadow, in legacy browsers you get all screwed up text.

    In the case of this one, it shows how sluggard the W3C is getting, since Edge, FF, Chrome, and Webkit ALL support it as -webkit-background-clip and -webkit-text-fill-color. They don't even bother with their own browser prefixes anymore using -webkit- in ALL of them... with the non-prefixed versions STILL not even "really" supported since the W3C still hasn't accepted it as spec. :/


    Ooh, that is probably WAY out of date, by like a decade. I'll toss that on my to-do list.

    That's what really rubbed me the wrong way about it. I love the tech and how it works, in many ways it makes flex look outright "too complex for its own good"... but that name makes you think of techniques it has nothing to do with... well, apart from the fact you COULD use it that way, but it's not meant for JUST that way.

    Yeah, his point #2 under the vs. comparison is mostly BS. Not sure where he got that idea, but that's likely a failure to grasp how either of them works... likely not understanding that flex can do it too through "order" and "flex-wrap". But again, flex is -- perhaps needlessly -- complex with far too many different declarations and models involved for what SHOULD be a relatively simple process. There have been times trying to use flex I've said "screw it" and gone back to floats with the "negative margin' trick out of expediency.

    IE -- all versions -- is around 8% and dropping according to most statistics, but that's worldwide. The number is SHOCKINGLY higher in the US, but that's hardly a shock given the average American is for all intents and purposes these days nothing more than Luddites. It's like at least half this damned country wants a return to the middle ages.
     
    deathshadow, Jun 24, 2019 IP
  9. pxgfx

    pxgfx Well-Known Member

    Messages:
    93
    Likes Received:
    24
    Best Answers:
    0
    Trophy Points:
    100
    #9
    Now I really want to learn more! Thank you so much!!

    PS -- Will wait for the template/screen ... TIA! =D
     
    pxgfx, Jun 25, 2019 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #10
    I just looked at them, and there are no significant changes I make there. The HTML file just loses the ".0" from initial-scale, and I uploaded the current "Starting point" screen.css I use and there are no major changes there either.

    That's what I start from for most sites. Actually, I start with a lot less than that since there's NOTHING inside <body> that I start out with pre-defined. When I'm working <body> starts out empty.
     
    deathshadow, Jun 26, 2019 IP
  11. Aaron Grayson

    Aaron Grayson Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #11
    You have given very valuable and helpful information. Looking forward to your future posts..

    Click here to visit my profile
     
    Aaron Grayson, Jun 26, 2019 IP
  12. pxgfx

    pxgfx Well-Known Member

    Messages:
    93
    Likes Received:
    24
    Best Answers:
    0
    Trophy Points:
    100
    #12
    I want to learn more about EM. How did you come up with font-size:0.937em?

    What do you think about sending box-sizing:border-box to * in the reset?
     
    pxgfx, Jun 27, 2019 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    Should be 0.9375, which is 15/16ths, but I take a hair off of it because on OSX it kerns wider if it's the exact amount with helvetica, resulting in different word-wrapping behaviors. You know crApple, anything to preserve glyph shape, who cares if the actual kerning metric is right, or if it's actually legible. Just make everything uselessly bold and blurry, because that looks SO much better.

    I do the same with the 14px equivalent for "normal / 96dpi / 100% / Win Vista+ Small / pick a huffing name already" users, using 85% instead of the exact 87.5% to adjust for kerning and rendering difference between browsers.

    EM starts out on BODY as whatever the user font size preference is -- or at least that's how it's SUPPOSED to work. From there it's based on the current font-size. The thing is, the user can change what they want to see for EM separate from zoom, so they don't have to keep dicking with zoom and just get well written pages properly. This is a behavior that PX doesn't provide.

    But let's take that 15/16ths example. On MOST computers that will give us 15px... but on the machine I'm on right now where my font preference is the "IBM 8514 / Windows 3.1 through XP "large" / Vista/newer "medium" / 125% / 120dpi / Pick a huffing name already" that is 20px, 15/16ths of 20px delivers 18.75px, which all browsers round (mostly) to 19px... though beware FF is inconsistent with everyone else when it comes to fractions. If I was on my media center which is set to Windows Vista/newer large -- aka 24px -- I get 22.5, which most browsers treat as 23 and FF treats as 22 with 23 spacing.

    All without ever having to touch the zoom. This is why your font-size, line-height, declared widths, media queries, etc, etc, should be in EM where possible.

    the thing to remember about EM is they are multiplicative. If the browser/system font is 16px::

    
    h1 { font-size:2em; } /* 32px */
    h1 span { font-size:0.5em; } /* 16px */
    h2 { font-size:1.5em; } /* 24px */
    h2 span { font-size:0.5em; } /* 12px */
    
    Code (markup):
    See how the span inside the H1 and H2 are relational to the parent, and not BODY? In theory REM is in relation to body, but it ignores the system metric and is stuck at 16px in some OS specific versions of FF, which is why I don't consider REM "ready for prime time". Of course on the machine I'm on right now that would be 40px / 20px / 30px / 15px, and on my media center that would be 48px / 24px / 36px / 18px respectively.

    Side note, percentage font-size is just em * 100. Something to be careful of is that % is something different on nearly every element!

    EM is the most accessible of font-sizes. As I often joke the WCAG says to use EM, so use 'em! It does allow for other types in isolated cases, but most of those are in controlled environments where the user can't or wouldn't change the size... basically, NOT a website.

    This scalability of design "just works" once you're used to it, and it's really not that hard to do / plan for. Just as an example, one of my older sites (the first I ever made responsive) when viewed on a "normal" computer without the font-size changed looks like this:

    https://cutcodedown.com/images/ewiUSB/ewiUsbComNormal96.jpg

    But at large fonts / 120dpi / 125% / Win Vista+ medium fonts / 20px / Pick a name already, it looks like this:

    https://cutcodedown.com/images/ewiUSB/ewiUsbComNormal120.jpg

    Note that whilst the fonts are 25% larger as is the max-width, the images did not change size. Hence this is NOT a level of zoom, it's accessible font scaling. That's what EM delivers.

    As a rule of thumb I dislike using *, and only do so for actual bugfixes like legacy mobile that doesn't know what to do with a viewport META.

    My biggest issue with putting that into a reset, is it is NOT a value that is inconsistent cross-browser, as the proper CSS box model is consistent all the way back to IE6 so long as you have a DOCTYPE declaration. That's not a reset's "job" and reeks of the type of nonsense that resulted in "reset reloaded" being a fat bloated mess that's damned near a framework. ... and if you haven't noticed, I have a painfully low opinion of "frameworks". I hear the word I cringe, and start looking for the door.

    More than that though, is that many of the same people advocating doing that, are the same clowns who spent two decades bitching about IE's "broken" box model... something that ONLY was an issue if you omitted a DOCTYPE or in IE5.x -- yet you STILL heard people say "broken" or "stupid" box model in reference to the IE "quirks mode" behavior... The EXACT SAME BEHAVIOR as box-sizing:border-box;. If it was so broken and bad, why are they tripping over their own feet in a mad rush to throw it at everything?

    It also adds more rules that have to be checked on EVERYTHING, this can negatively impact render times. It's often funny as the people who advocate doing things like that are the ones who say things like "move your initial style into the markup in a <style> tag" pissing on caching models over some nutjob worry about "render time" then advocate doing things that impact render time like throwing endless pointless classes at everything, using the * selector to throw rules at everything, and other things that ACTUALLY negatively impact load times? No... Bullcookies. Again, maybe if they weren't wasting 100k of markup to do 16k's job, 500k of CSS to do 48k's job, two to five megabytes of scripttardery to do 128k's job (if there should even BE JavaScript), and four to six dozen separate files to do 3 files job, they wouldn't be resorting to borked trash like style in the markup, dumbass frameworks that use classes to put style in the markup, putting baby static sites into CDN's, and dicking around with cache-control headers.

    It is a useful property in a handful of corner cases, like trying to make a padded input that's 100% width of the parent... but there is no legitimate reason to throw the LEGACY IE 5 box model at EVERYTHING. If it comes up often enough on enough elements for it to require a global "set it and forget it" you're probably doing something wrong!

    Like many things, doing so just reeks of people who really seem to miss the pre-CSS HTML 3.2 / 4 Tranny days.
     
    deathshadow, Jun 27, 2019 IP