How to make HTML/CSS code clean and optimized?

Asked

Viewed 2,300 times

-4

Wanted tips to apply in my learning. I am a beginner and always hear talk of clean code.

  • 1

    Just comment, identar, and organize the code well, also keep them in folders not to leave everything spread, avoid to the maximum the famous POG programming oriented to gambiarra.

  • Take a look at this link and you can help: https://browserdiet.com/pt/

2 answers

4


There are no rules for a clean code. Neither in the markup languages as you are, nor in the programming.

Target audience of source code: teamwork is OP!

It is necessary to take into account who will read your code, it is important to define between the team (if there are) conventions, because there are several ways to do the same thing.

1. Use lower case letters in widgets. HTML5 allows mixing elements in upper and lower case letters.

You can use it like this:

<DIV> 
  <p>Uma vaga noção de tudo, e um conhecimento de nada. — Charles Dickens</p>
</DIV>

or:

<Div> 
  <p>Sábio é aquele que conhece os limites da própria ignorância. — Sócrates</p>
</DIV>

or even:

<div> 
  <p>Bom humor. A forma mais simples de superar os problemas. — Rui Barbosa</p>
</div>

It is recommended to use the elements name as in the last example, in lower case, according to the w3schools, for:

  • Mix uppercase and lowercase letters is bad.
  • Developers usually use it in lower case letters. (as occurs in XHTML)
  • Lowercase letters seem more organized.
  • Finally, lower-case writing is easier and faster to write.

2. Close all items. HTML5 allows us not to close all elements.

<section>
  <p>Todos os seus sonhos podem se tornar realidade se você tem coragem para persegui-los. — Walt Disney
</section>

In the above example, the element p was opened, but was not closed. In a more beautiful and organized code (remembering, you can and must define your own conventions with your team these presented are tips, which can serve as a starting point) would be so:

<section>
  <p>Eu não falhei. Só descobri 10 mil caminhos que não eram o certo. — Thomas Edison</p>
</section>

3. Do not save on image attributes The alt, for example it is important because there will be times that for some reason the image you have defined cannot be displayed, either because it has changed path, or because it no longer exists, in these cases your description will be displayed.

Already setting the height and width of the image is important because the browser will reserve space for image even before it is loaded, reducing the render time avoiding repaints and reflows unnecessary.

A bad example of an image would be:

<img src="minha-imagem.jpg">

A good example would be:

<img src="minha-imagem.jpg" alt="Descrição da imagem" style="width:128px;height:128px" />

4. Semantics can make your code organized. I won’t get into the merit of explaining the semantics here, but you can read by clicking here (is worth it! ). In short, it divides your page internally, without affecting the look. This division makes your code more organized and segmented, if you want more information, read the link I left above.


There are several standards to be established, including for CSS style sheets.

Style sheets can be short, in one row only, like this:

p.intro {font-family: Verdana; font-size: 16em;}

And they can be written long, like this:

body {
  background-color: lightgrey;
  font-family: "Arial Black", Helvetica, sans-serif;
  font-size: 16em;
  color: black;
}

Now it remains for you to choose how you should set the default, it is good to take some parameters into consideration: (remember the beginning, are not rules)

  • Very long lines are not cool and can be a little difficult to handle, so avoid.
  • The opening key ({) can be placed on the same line as the selector.
  • Use quotes only between values that contain space.
  • Use the key to close the block (}) on the line just below the end of the code, avoiding spaces.
  • Use the semicolon after each property, even the last one.

See the example of a beautiful HTML code:

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">

    <title>Portfolio | Chris Coyier</title>

    <!--[if !IE]><!-->
        <link rel="stylesheet" href="/css/main.css" />
    <!--<![endif]-->

    <!--[if gte IE 7]>
        <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen, projection" />
    <![endif]-->

    <!--[if IE 6]>
        <link rel="stylesheet" type="text/css" href="http://universal-ie6-css.googlecode.com/files/ie6.0.3.css" media="screen, projection" />
    <![endif]-->
</head>

<body id="home">

    <header>
        <a id="logo" href="/">Site Title</a>
        <div id="slogan">web craftsman, blogger, author, speaker</div>

        <nav>
            <?php include("inc/main-menu.php"); ?>
        </nav>
    </header>

    <section class="container">

        <article>
            <h1>Hipsters</h1>

            <img src="//chriscoyier.net/images/hipster.jpg" alt="Hipster and Company" height="120" width="570" />

            <p>You can&#8217;t dress up as a hipster for Halloween. Their attire is already so bizarre that there isn&#8217;t an
            exaggeration of it that looks like a costume. It would just look like you are another hipster about to read a poem about reading poems.</p>

            <h2>Secondary Title</h2>
            <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
        </article>

        <article>
            <!-- Additional Article -->
        </article>

    </section>

    <aside>
        <h3>My Major Projects</h3>
        <dl>
            <dt><a href="http://aremysitesup.com">Are My Sites Up?</a></dt>
            <dd>Monitor your sites</dd>

            <dt><a href="http://css-tricks.com">CSS-Tricks</a></dt>
            <dd>A web design community</dd>

            <dt><a href="http://digwp.com">Digging Into WordPress</a></dt>
            <dd>Learn about WordPress</dd>
        </dl>
    </aside>

    <footer class="container">
        <h4>People I Enjoy</h4>
        <ul class="col">
            <li><a href="http://fastfoodreviewed.com">Jesse Lynch</a></li>
            <li><a href="http://jeffcampana.com">Jeff Campana</a></li>
            <li><a href="http://perishablepress.com">Jeff Starr</a></li>
        </ul>
        <ul class="col">
            <li><a href="http://davidwalsh.name">David Walsh</a></li>
            <li><a href="http://thestrategicretreat.com">Jeff Penman</a></li>
            <li><a href="http://http://shiftedfrequency.com">Richard Felix Jr.</a></li>
        </ul>

        <h4>Sandwiches</h4>
        <ul class="col container" id="sandwich-list">
            <li><a href="http://jimmyjohns.com">Jimmy Johns</a></li>
            <li><a href="http://subway.com">Subway</a></li>
            <li><a href="http://potbelly.com">Potbelly</a></li>
        </ul>

        &copy;2007-<?php echo date("Y"); ?> Chris Coyier
    </footer>

    <script src='//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
    <script src='/js/main.js'></script>

    <!-- Google Analytics Code -->
    <?php include_once("inc/analytics.php"); ?>

</body>

</html>

Source: CSS-Tricks

He’s handsome because he follows a pattern, from start to finish, all elements are being closed, images all argued, semantic, among other factors.

Readability and maintenance

Can an unreadable code work? Yes.

So says Robert C. Martin in Clean Code (book that has already been quoted here). The question is why shouldn’t we write bad code? The answer is maintenance.

Resorting to what has already been said above, the target audience of your code is your team, and if there is a team, they will also provide maintenance on the code that has been written.

A well-written, documented, readable code will save maintenance time, leading to productivity.


Talking about this subject is very delicate because it involves opinion, since there is no official HTML/CSS guide. I tried to leave the slightest argument and more theory, explaining why one thing is preferable to the other. I leave you some links that can help define conventions or even for further reading:

1

  • Well, maybe it’s good to start applying to the good programming practices that the W3C provides because with these practices it is possible to realize future maintenance and be interpreted by other programmers.
  • Another practice for the CSS is to apply to Dynamic Style Sheet Languages, there are many tools like SASS, LESS, STYLUS and among others because you will work with the hierarchy of elements and the repetition of codes, and these tools try to minimize repetition.
  • Finally, to optimize, it is good to learn the Task Automation like the Gulp (In this case it will be necessary to learn about Nodejs in this step), it brings several tools that will decrease the files without losing quality, will check the appropriate prefixes and arrange them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.