How to avoid repeating html and css commands?

Asked

Viewed 1,036 times

1

How do I not repeat the HTML and CSS code of a site’s structure? For example, I did the structure of a web page and I want that structure to be applied to the other 5 pages that I will create for that site. Follow the page print: inserir a descrição da imagem aqui

For this I created an HTML file and a CSS. To replicate this structure to the other pages I created HTML and CSS files for each of the other 5 pages I copied and pasted the codes of this structure into them. But this is very repetitive, I think there’s a more efficient way to do this. If I change anything in this sidebar, I took that change in the other 5 files, for example.

Is there any method to avoid this repetition?

  • 3

    I think only with PHP, or copy Paste.

  • 2

    You can use JS for this, take a look at the jQuery load

  • @Rafaelaugusto The problem of .load() jQuery only works online.

  • For me the best solution is to copy the file and paste inside the folder with another name. It is worth remembering that all the links related to css, js, images... Shall be valid

  • 1

    Study more about includes in PHP, it does exactly what you want. Generating an equal html for all elements being changed in only one file.

3 answers

2

This solution is only if you want the same content in other pages. If it’s just the styling just import the same file CSS on the other pages and set the same #id's or .classes us same elements.

Can do using JQuery.

Suppose you have content in the file menu.html which must be on all its pages.

Simply include the code below on your other pages that should have the content of menu.html:

    <script src="jquery.js"></script> <!-- Importar biblioteca do Jquery -->
    <script> 
    $(function(){
      $("#includedContent").load("menu.html"); // incluir conteúdo do menu.html na div com id #includedContent
    });
    </script> 
    <div id="includedContent"></div> <!-- o menu.html será incluído nessa div -->

Source: https://stackoverflow.com/questions/8988855

Another way: https://www.w3schools.com/howto/howto_html_include.asp

  • I just wanted the same styling. I import the css file, but the problem is still the repetition of html, are 80 lines of code. I even tried using Jquery, but I can’t change the contents of my <article>.

2

I highly recommend that you use Gulp or Grunt for this. With it you can use a template engine such as nunjucks, Pug or handlebars. They facilitate a lot in the creation of the front-end.

I created a Boilerplate, can be useful to you: https://github.com/diogocosta/basement

2

In addition to the way Diego Costa commented, there’s an old technique called Server Side Includes. With Iframe it is also possible to achieve the same result.

Here has more resolutions on the same problem

Browser other questions tagged

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