HTML / CSS

Treinamento da InfoJr - UFBA

Criado por Mateus Cordeiro / Gabriel Gomes / Vinicius Dias / Victor Copque

Front-End vs Back-End

Em ciência da computação, front-end e back-end são termos generalizados que referem-se às etapas inicial e final de um processo. O front-end é responsável por coletar a entrada em várias formas do usuário e processá-la para adequá-la a uma especificação em que o back-end possa utilizar. O front-end é uma espécie de interface entre o usuário e o back-end. Ambos podem estar distribuídos entre um ou mais sistemas.

HTML is a markup language for describing web documents (web pages).


  • HTML stands for Hyper Text Markup Language
  • A markup language is a set of markup tags
  • HTML documents are described by HTML tags
  • Each HTML tag describes different document content

Arquivo .html

Estrutura Básica


<!DOCTYPE html>
<html>
    <head>
        <title><!-- Título da Página --></title>
    </head>
    <body>
        <!-- Corpo da Página -->
    </body>   
</html>
                        

DOCTYPE


<!DOCTYPE html>
                        

The <!DOCTYPE html> declaration must be the very first thing in your HTML document, before the </html> tag.

The <!DOCTYPE html> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.

There are three different <!DOCTYPE html> declarations in HTML 4.01. In HTML5 there is only one.

<html>


<html></html>
                        

The <html> tag tells the browser that this is an HTML document.

The <html> tag represents the root of an HTML document.

The <html> tag is the container for all other HTML elements (except for the tag).

<title>


<title></title>
                        

The <title> tag is required in all HTML documents and it defines the title of the document.

  • defines a title in the browser toolbar
  • provides a title for the page when it is added to favorites
  • displays a title for the page in search-engine results

<body>


<body></body>
                        

The <body> tag defines the document's body.

The <body> element contains all the contents of an HTML document, such as text, hyperlinks, images, tables, lists, etc.

Parágrafos, cabeçalhos e texto

p

See the Pen JqDjv by Mateus Cordeiro (@mateuscgc) on CodePen.

cabeçalhos (headers)

See the Pen HGKof by Mateus Cordeiro (@mateuscgc) on CodePen.

blackquote e q

See the Pen aBhLF by Mateus Cordeiro (@mateuscgc) on CodePen.

pre

See the Pen xdKvy by Mateus Cordeiro (@mateuscgc) on CodePen.

b, strong, i, em

See the Pen zBKfn by Mateus Cordeiro (@mateuscgc) on CodePen.

dfn, cite, var, code, samp, kdb

See the Pen CGcwy by Mateus Cordeiro (@mateuscgc) on CodePen.

br, hr

See the Pen iHcog by Mateus Cordeiro (@mateuscgc) on CodePen.

section, article

See the Pen tDuvo by Mateus Cordeiro (@mateuscgc) on CodePen.

The <section> and <article> tags are new in HTML5.

Links

<p>This is a <a href="www.google.com">link</a></p>

See the Pen gojxF by Gabriel Gomes (@Gabrielgqa) on CodePen.

In HTML, links are defined with the <a> tag.

Links - Colors and Icons

<p>This is a <a href="www.google.com.br">link</a></p>

See the Pen KJCut by Gabriel Gomes (@Gabrielgqa) on CodePen.

The link can be styled.

Links - Relative Address

See the Pen plHnC by Mateus Cordeiro (@mateuscgc) on CodePen.

Links - Types of Links

See the Pen umqtx by Mateus Cordeiro (@mateuscgc) on CodePen.

There are some types of links, including mailto and tel

<div>

The <div> tag defines a division or a section in an HTML document.

The <div> tag is used to group block-elements to format them with CSS.

See the Pen tbeFB by Mateus Cordeiro (@mateuscgc) on CodePen.

<span>

The <span> tag is used to group inline-elements in a document.

The <span> tag provides no visual change by itself.

The <span> tag provides a way to add a hook to a part of a text or a part of a document.

See the Pen DwHua by Mateus Cordeiro (@mateuscgc) on CodePen.

Images

In HTML, images are defined with the <img> tag.

The <img> tag is empty, it contains attributes only, and does not have a closing tag.

The src attribute defines the url (web address) of the image:


<img src="url">
                        

some attributes of tag <img>

The alt attribute specifies an alternate text for the image, if it cannot be displayed.

The value of the alt attribute should describe the image in words:


<img src="html5.gif" alt="The official HTML5 Icon">
                        

some attributes of tag <img>

You can use the style attribute to specify the width and height of an image.

The values are specified in pixels (use px after the value):


<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px">
                        

some attributes of tag <img>

Alternatively, you can use width and height attributes.

The values are specified in pixels (without px after the value):


<img src="html5.gif" alt="HTML5 Icon" width="128" height="128"">
                        

Image as Link

It is common to use images as links:


<a href="default.asp">
  <img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0">
</a>
                        

<table>

Tables are defined with the <table> tag.

Tables are divided into table rows with the <tr>tag.

Table rows are divided into table data with the <td> tag.

A table row can also be divided into table headings with the <th>tag.

Example

<table>
                          <tr>
                            <th>Firstname</th>
                            <th>Lastname</th> 
                            <th>Points</th>
                          </tr>
                          <tr>
                            <td>Eve</td>
                            <td>Jackson</td> 
                            <td>94</td>
                          </tr>
                          <tr>
                            <td>Ada<d>
                            <td>Jackson</td> 
                            <td>78</td>
                          </tr>
                        </table>

See the Pen Izrad by Gabriel Gomes (@Gabrielgqa) on CodePen.

<thead>, <tfoot>, and a <tbody>

An HTML table with a <thead>, <tfoot>, and a <tbody> element:

<table>
                          <thead>
                            <tr>
                              <th>Month</th>
                              <th>Savings</th>
                            </tr>
                          </thead>
                          <tfoot>
                            <tr>
                              <td>Sum</td>
                              <td>$180</td>
                            </tr>
                          </tfoot>
                          <tbody>
                            <tr>
                              <td>January</td>
                              <td>$100</td>
                            </tr>
                            <tr>
                              <td>February</td>
                              <td>$80</td>
                            </tr>
                          </tbody>
                        </table>

See the Pen Aockd by Gabriel Gomes (@Gabrielgqa) on CodePen.

Table Attributes

Colspan: To make a cell span more than one column, use the colspan attribute:

<table style="width:100%">
                          <tr>
                            <th>Name</th>
                            <th colspan="2">Telephone</th>
                          </tr>
                          <tr>
                            <td>Bill Gates</td>
                            <td>555 77 854</td>
                            <td>555 77 855</td>
                          </tr>
                        </table>

See the Pen IECjo by Gabriel Gomes (@Gabrielgqa) on CodePen.

Table Attributes

Rowspan: To make a cell span more than one row, use the rowspan attribute:

<table style="width:100%">
                          <tr>
                            <th>First Name:</th>
                            <td>Bill Gates</td>
                          </tr>
                          <tr>
                            <th rowspan="2">Telephone:</th>
                            <td>555 77 854</td>
                          </tr>
                          <tr>
                            <td>555 77 855</td>
                          </tr>
                        </table>

See the Pen wKLuC by Gabriel Gomes (@Gabrielgqa) on CodePen.

Forms

HTML forms are used to pass data to a server.

An HTML <form> can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A <form> can also contain select lists, textarea, fieldset, legend, and label elements.

The <form> tag is used to create an HTML <form>:


<form>
.
input elements
.
</form>
                        

Form - The Input Element

The most important form element is the <input> element.

The <input> element is used to select user information.

An <input> element can vary in many ways, depending on the type attribute. An <input> element can be of type text field, checkbox, password, radio button, submit button, and more.

The most common input types are described below.

Text Fields

<input type="text"> defines a one-line input field that a user can enter text into:

<form>
                        First name: <input type="text" name="firstname"><br>
                        Last name: <input type="text" name="lastname">
                        </form>

See the Pen ynArH by Gabriel Gomes (@Gabrielgqa) on CodePen.

Password Field

<input type="password"> defines a password field:

<form>
                        Password: <input type="password" name="pwd">
                        </form>

See the Pen jarlv by Gabriel Gomes (@Gabrielgqa) on CodePen.

Radio Buttons

<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of choices:

<form>
                        <input type="radio" name="sex" value="male">Male<br>
                        <input type="radio" name="sex" value="female">Female
                        </form>

See the Pen hxzqb by Gabriel Gomes (@Gabrielgqa) on CodePen.

Checkboxes

<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited number of choices.

<form>
                        <input type="radio" name="sex" value="male">Male<br>
                        <input type="radio" name="sex" value="female">Female
                        </form>

See the Pen hxzqb by Gabriel Gomes (@Gabrielgqa) on CodePen.

Submit Button

<input type="submit"> defines a submit button.

A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input:

<form name="input" action="demo_form_action.asp" method="get">
                        Username: <input type="text" name="user">
                        <input type="submit" value="Submit">
                        </form>

See the Pen ioIyk by Gabriel Gomes (@Gabrielgqa) on CodePen.

Selects

The <select> element is used to create a drop-down list.

The <option> tags inside the <select> element define the available options in the list.

<select>
                        <option value="volvo">Volvo</option>
                        <option value="saab">Saab</option>
                        <option value="mercedes">Mercedes</option>
                        <option value="audi">Audi</option>
                        </select>

See the Pen iuGDs by Gabriel Gomes (@Gabrielgqa) on CodePen.

Textarea

The <textarea> tag defines a multi-line text input control.

A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).

The size of a text area can be specified by the cols and rows attributes, or even better; through CSS' height and width properties.

<textarea rows="4" cols="50">
                        At w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies. 
                        </textarea>

See the Pen rjsCv by Gabriel Gomes (@Gabrielgqa) on CodePen.

Input Types

HTML5 has several new input types for forms. These new features allow better input control and validation.

This chapter covers the new input types:

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • numember
  • rage
  • search
  • tel
  • time
  • url
  • week

Examples of use

<form>
                          <p>Type number</p>Quantity:
                          <input type="number" name="points" min="0" max="100" step="10" value="30">
                        </form>
                        <form>
                          <p>Type date</p>Birthday:
                          <input type="date" name="bday">
                        </form>
                        <form>
                          <p>Type color</p>Select your favorite color:
                          <input type="color" name="favcolor">
                        </form>
                        <form>
                          <p>Type range</p>
                          <input type="range" name="points" min="0" max="10">
                        </form>
                        <form>
                          <p>Type mail</p>E-mail:
                          <input type="email" name="email">
                        </form>
                        <form>
                          <p>Type tel</p>Telephone:
                          <input type="tel" name="usrtel">
                        </form>

See the Pen BoIeb by Gabriel Gomes (@Gabrielgqa) on CodePen.

Other Attributes

An HTML form with autocomplete on (and off for one input field):

<form action="demo_form.asp" autocomplete="on">
                        First name:<input type="text" name="fname"><br>
                        Last name: <input type="text" name="lname"><br>
                        E-mail: <input type="email" name="email" autocomplete="off"><br>
                        <input type="submit">
                        </form>

See the Pen kuzvd by Gabriel Gomes (@Gabrielgqa) on CodePen.

The novalidate attribute is a boolean attribute.

When present, it specifies that the form-data (input) should not be validated when submitted.

<form action="demo_form.asp" novalidate>
                        E-mail: <input type="email" name="user_email">
                        <input type="submit">
                        </form>

See the Pen gHadD by Gabriel Gomes (@Gabrielgqa) on CodePen.

Other Attributes

The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).

<form action="demo_form.asp">
                          <input type="text" name="fname" placeholder="First name"><br>
                          <input type="text" name="lname" placeholder="Last name"><br>
                          <input type="submit" value="Submit">
                        </form> 

See the Pen HnGmf by Gabriel Gomes (@Gabrielgqa) on CodePen.

The required attribute is a boolean attribute.

When present, it specifies that an input field must be filled out before submitting the form.

<form action="demo_form.asp">
                        Username: <input type="text" name="usrname" required>
                        <input type="submit">
                        </form>

See the Pen svqDu by Gabriel Gomes (@Gabrielgqa) on CodePen.

Other Attributes

The autofocus attribute is a boolean attribute.

When present, it specifies that an <input> element should automatically get focus when the page loads.

<form action="demo_form.asp">
                          First name: <input type="text" name="fname" autofocus><br>
                          Last name: <input type="text" name="lname"><br>
                          <input type="submit">
                        </form>

See the Pen LBEwq by Gabriel Gomes (@Gabrielgqa) on CodePen.

Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors, spacing) to Web documents.

  • Styles define how to display HTML elements
  • Styles were added to HTML 4.0 to solve a problem
  • External Style Sheets can save a lot of work
  • External Style Sheets are stored in CSS files

Estrutura Básica


Seletor {
    propriedade : valor ;
    propriedade : valor ;
    propriedade : valor ;
}
                        

Inline CSS


<div style="width: 200px; height: 200px; border-radius: 6px; display: block;">
    <!-- mais html -->
<div>
                        

Embendded CSS


<!DOCTYPE html>
<html>
    <head>
        <title><!-- Título da Página --></title>
        <style>
            body {
                background-color: linen;
            }
            h1 {
                color: maroon;
                margin-left: 40 px;
            } 
        </style>
    </head>
    <body>
        <!-- Corpo da Página -->
    </body>   
</html>
                        

CSS Externo


<!DOCTYPE html>
<html>
    <head>
        <title><!-- Título da Página --></title>
        <link rel="stylesheet" type="text/css" href="../css/stylesheet.css">
    </head>
    <body>
        <!-- Corpo da Página -->
    </body>   
</html>
                        

body {
    background-color: linen;
}

h1 {
    color: maroon;
    margin-left: 40 px;
} 
                        

Seletores CSS

Seletor Universal *


* {
    margin : 0px ;
    color : blue ;
}
                        

.Class Seleciona todos os elementos com determinada classe


.msg-box {
    width: 200px;
    height: 100px;
    padding: 20px;
}
                        

#Id Seleciona o elemento com determinada id


#news {
    float: left;
    position: absolute;
    display: inline;
}
                        

tag Seleciona todos os elementos da tag.


p {
    color: red;
}
                        

tag1, tag2 Seleciona todos os elementos da lista.


div, .box, #comentario {
    font-size: 20px;
    font-family: arial;
}
                        

div {
    font-size: 20px;
    font-family: arial;
}
.box {
    font-size: 20px;
    font-family: arial;
}
#comentario {
    font-size: 20px;
    font-family: arial;
}
                    

tag1 tag2 Seleciona todos os tag2 dentro de tag1.


.msg-box p {
    color: pink;
    text-align: center;
}
                        

tag1 > tag2 Seleciona todos os tag2 que são filhos de tag1.


#menu > div {
    width: 100px;
    margin-top: 20px;
}
                        

tag1 + tag2 Seleciona todos os tag2 ques estão imediatamente depois de tag1.


.title + .subtitle{
    color: #777;
    font-wheight: bold;
}
                        

tag1 ~ tag2 Seleciona todos os tag2 que apareceram depois de pelo menos um tag1


p ~ ul {
    background: #ff0000;
}
                        

tag:active Seleciona um elemento ativo


a {
    background-color: blue;
}
a:active {
    background-color: yellow;
}
                        

tag:hover Seleciona o elemento quando o mouse está em cima dele


div {
    width: 70px;
}
div:hover {
    width: 100px;
}
                        

tag:first-child Selecionam as tag que sejam a primeira filha de seus pais


.box:first-child {
    background-color: red;
    color: grey;
}
                        

tag:Last-Child Seleciona as tag que são a ultima filha de seus pais


.box:last-child {
    background-color: red;
    color: grey;
}
                        

tag:nth-child(x)Seleciona o elemento tag que é filha de número x


.box:nth-child(10) {
    background-color: red;
    color: grey;
}
                        

Acesse a lista completa de seletores aqui!

Unidades

Em CSS temos várias unidades de medida: px, pt, em, rem, %, entre outras.

Pixel

Você utiliza px para definir a largura de um elemento, o tamanho do texto, a espessura da borda e outras coisas. A unidade px é utilizada para definir o tamanho dos textos por que é a medida mais exata que você pode encontrar. Por não ser uma medida variável, são fáceis de controlar.

<p>Esse é o texto</p>

See the Pen pJLaf by Gabriel Gomes (@Gabrielgqa) on CodePen.

EM

O problema de utilizar fonts em em é que elas são variáveis como a porcentagem. Diferentemente da utilização de pixels, temos que fazer um pouco de matemática para planejar nossas unidades no projeto. Não é nada de outro mundo, então pare de preguiça.

O cálculo: 20 ÷ 16 = 1.25em

<p>Esse é o texto</p>

See the Pen nBvKq by Gabriel Gomes (@Gabrielgqa) on CodePen.

Porcentagem

O uso do % é bem semelhante ao do EM. Assim, ele é também variável de acordo com o contexto.

<p>Esse é o texto</p>

See the Pen txnqu by Gabriel Gomes (@Gabrielgqa) on CodePen.

Seria interessante se o valor do contexto fosse sempre o mesmo, não é?

REM

A REM sempre terá o valor de contexto do ROOT (é isso que significa o R do REM), ou seja, sempre o body… Os valores ficariam assim se referenciando pelo body.

Fontes

Em CSS temos algumas propriedades específicas para estilização das fontes, são elas:

  • color: cor da fonte;
  • font-family: tipo de fonte
  • font-size:tamanho da fonte
  • font-style: estilo da fonte
  • fontes maiúsculas de menor altura
  • font-weight: quanto mais escura a fonte é (negrito)
  • font: maneira abreviada para todas as propriedades
  • Exemplo de uso

    <p class="fs">Texto formatado</p>
                            <p class="ff">Texto formatado</p>
                            <p class="fv">Texto formatado</p>
                            <p class="fst">Texto formatado</p>
                            <p class="fw">Texto formatado</p>
                            <p class="f">Texto formatado<p>

    See the Pen BzADb by Gabriel Gomes (@Gabrielgqa) on CodePen.

    Texto

    Em CSS temos algumas propriedades específicas para estilização detextos, são elas:

  • color: cor do texto
  • letter-spacing: espaçamento entre letras
  • word-spacing: espaçamento entre palavras
  • text-align: alinhamento do texto
  • text-decoration: decoração do texto
  • text-ident: recuo do texto
  • text-transform: forma das letras
  • direction: direção do texto
  • white-space: como browser trata os espaços em branco
  • Exemplo de uso

    <p class="cl">Texto formatado</p>
                            <p class="ls">Texto formatado</p>
                            <p class="ws">Texto formatado</p>
                            <p class="ta">Texto formatado</p>
                            <p class="td">Texto formatado</p>
                            <p class="tt">Texto formatado</p>
                            <p class="dc">Texto formatado</p>

    See the Pen fsBwL by Gabriel Gomes (@Gabrielgqa) on CodePen.

    Cores e Planos de Fundo

    Como já vimos, em CSS é possível alterar as cores. Isso serve para qualquer elemento HTML.

    Para o valor da cor temos diferentes tipos de medida:

    
    I { color: red }
    I { color: #FF0000 }
    I { color: rgb (255, 0, 0) }
                            

    Backgronds

    A propriedade background define as características (os valores na regra CSS) do fundo dos elementos HTML. Elas são:

  • background-color: cor do fundo
  • background-image: imagem de fundo
  • background-repeat: maneira como a imagem de fundo é repetida
  • background-attachment: se a imagem de fundo "rola" ou não com a tela
  • background-position: como e onde a imagem de fundo é posicionada
  • background: forma abreviada
  • Exemplo de uso

    <div id="bc"></div>
                            <div id="bi"></div>

    See the Pen cHJph by Gabriel Gomes (@Gabrielgqa) on CodePen.

    Cursor

    Estiliza o cursor do mouse.

    Alguns dos valores são:

  • auto: Aspecto idêntico ao cursor padrão no tag que tem o atributo, não muda nada.
  • default: Cursor padrão do navegador.
  • pointer: Cursor em forma de mão com o dedo reto.
  • text: Cursor de edição de texto.
  • help: Cursor de ajuda.
  • wait: Cursor de espera.
  • progress: Cursor de progressão.
  • move: Cursor de deslocamento.
  • crosshair: Cursor em forma de cruz.
  • A propriedade borda

    Esta propriedade é usada para definir o estilo, cor e espessura da borda do elemento.

    <p>Esse é um parágrafo</p>

    See the Pen tpaAq by Gabriel Gomes (@Gabrielgqa) on CodePen.

    
    .box {
        border: 3px solid yellow;
    }
                            
    
    .box {
        border-style: solid;
        border-width: 3px;
        border-color: yellow;
    }
                            

    Estilos de Bordas

    See the Pen border styles by Mateus Cordeiro (@mateuscgc) on CodePen.

    Adcionando bordas a lados especificos

    See the Pen gpJLm by Mateus Cordeiro (@mateuscgc) on CodePen.

    See the Pen oreiu by Mateus Cordeiro (@mateuscgc) on CodePen.

    Margens

    margin especifica um determinado espaçamento em volta de um elemento.

    See the Pen side borders by Mateus Cordeiro (@mateuscgc) on CodePen.

    Número de valores

    
    margin: 25px 50px 75px 100px;
    /*top margin is 25px*/
    /*right margin is 50px/
    /*bottom margin is 75px*/
    /*left margin is 100px*/
    
    margin: 25px 50px 75px;
    /*top margin is 25px*/
    /*right and left margins are 50px*/
    /*bottom margin is 75px*/
    
    margin: 25px 50px;
    /*top and bottom margins are 25px*/
    /*right and left margins are 50px*/
    
    margin: 25px;
    /*all four margins are 25px*/
                            

    Padding

    padding especifica um determinado espaçamento entre os limites do elemento e seu conteudo.

    See the Pen xiEej by Mateus Cordeiro (@mateuscgc) on CodePen.

    Número de valores

    
    padding: 25px 50px 75px 100px;
    /*top padding is 25px*/
    /*right padding is 50px/
    /*bottom padding is 75px*/
    /*left padding is 100px*/
    
    padding: 25px 50px 75px;
    /*top padding is 25px*/
    /*right and left padding are 50px*/
    /*bottom padding is 75px*/
    
    padding: 25px 50px;
    /*top and bottom padding are 25px*/
    /*right and left padding are 50px*/
    
    padding: 25px;
    /*all four margins are 25px*/
                            

    Estilizando Tabelas

    See the Pen HBxzG by Mateus Cordeiro (@mateuscgc) on CodePen.

    Position

    A propriedade position especifica o tipo de posicionamento de um elemento.

    
    position: static;
    position: absolute;
    position: fixed;
    position: relative;
    position: initial;
    position: inherit;
                            
    Exemplo

    Display

    A propriedade display especifica o tipo de caixa de um elemento html.

    
    display: inline; /*default*/
    display: block; /*Ex: <p>*/
    display: inline-block;
    display: list-item;
    display: none;
    display: initial;
                            
    Exemplo