Introduction to CSS: Learn to Style Your Web Pages from Scratch

Introduction:

Las Cascading Style Sheets, better known as CSS, are a fundamental tool in web design that allows you to give life and style to Internet pages. In this article, we'll explore the basic concepts of CSS, its syntax with simple examples, and the key terms surrounding this language.

đź’ˇ For this tutorial blog we need to have a knowledge of HTML, if not personally I recommend reading a little about this topic, here's a link to its documentation: https://developer.mozilla.org/es/docs/Web/HTML

CSS structure

The basic structure of a style file in CSS is quite simple, below is an example of what the structure of a style file looks like:


/* Comentario en CSS */

/* Estilos para el cuerpo de la página */
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    color: #333;
}

/* Estilos para los encabezados */
h1, h2, h3 {
    color: #0066cc;
}

/* Estilos para los párrafos */
p {
    margin-bottom: 10px;
}

/* Estilos para enlaces */
a {
    color: #990000;
    text-decoration: none;
}

/* Estilos para enlaces al pasar el ratĂłn sobre ellos */
a:hover {
    text-decoration: underline;
}




This basic structure consists of rule blocks, where each block has a selector that points to a specific type of HTML element, and within the block, like a summary, the CSS selects the HTML elements and tells them how they should be displayed, there are a series of properties and values that define how those elements should be displayed.

  • Comments in CSS are written between /* and / and are optional but can be useful for documenting your code.
  • Rule blocks start with a selector (such as Body, H1, P, unto, etc.) followed by a set of properties and values in braces {}.
  • Each property and value are separated by a colon (:) and end with a semicolon (;).
  • The rule blocks are separated by blank lines.

This is a basic structure, and complexity can increase depending on the number of styles and the organization of the project. In addition, comments and whitespace can be used to improve the readability and maintainability of the code.

Css selectors:

In CSS (Cascading Style Sheets), selectors are patterns used to select and apply styles to specific elements in an HTML document. Selectors allow you to point to one or more HTML elements and define how those elements should be viewed.

Types of Selectors

1. Element Selector:

CSS:


p {
	background-color: yellow;
    /* Estilos para párrafos */
}


Here's a representation of how it would be used directly in an HTML file




‍

2. Selector ID:‍

CSS:


#miElemento {
    /* Estilos para el elemento con ID "miElemento" */
}


HTML example:




3. Class Selector:

CSS:


.miClase {
    /* Estilos para todos los elementos con la clase "miClase" */
}


HTML:




4. Descendant Selector:

CSS:





HTML:




5. Child Selector:

CSS:




HTML:

Este párrafo tiene estilos porque es hijo directo de un div.

Este párrafo también tiene estilos.




6. Attribute Selector:

CSS:



input[type="text"] {
    /* Estilos para todos los elementos input de tipo texto */
}


HTML:




7. Universal selector

In CSS it is used as a universal selector and applies styles to all the HTML elements on the page. In this case, you're changing the text color to “red” for all the elements.


* {
  color: red;
/* Esta regla hace que todos los elementos HTML de la página tengan texto de color activo. */
}


Selector Specificity:

The specificity of selectors in CSS is a crucial concept for determining which style rules will prevail in the event of conflicts. It is calculated by assigning weighted values to the selectors, and the greater the specificity, the more weight the rule will have when applying styles. Hierarchy is essential, as it determines the priority of rules. Selectors such as ID have greater specificity than type or class selectors. Understanding these principles helps to resolve style conflicts and to write more effective and maintainable code.

  • Universal (*): It has low specificity.
  • Type (P, Div, etc.): It has low specificity.
  • Class (.class): It has greater specificity than type selectors.
  • ID (#id): It has even more specificity than classes.

Example of a specificity comparison:

  • #miId .my class: High specificity (1 ID, 1 class).
  • div .myClass: Moderate specificity (1 type, 1 class).
  • .my class.my other class: Moderate specificity (2 classes).
🚨 If two rules have the same specificity, the rule that appears later in the style sheet will prevail.

‍‍

Properties and Values

Here are some examples of CSS properties:

  1. Font color:
  • Property: colour
  • Value: This can be a color name (such as “red” or “blue”) or a hexadecimal code (such as "#ff0000" for red).
  1. Content background:
  • Property: Background
  • Value: Defines the background of an element. It can be a color, an image, and so on.
  1. Source:
  • Property: font-family
  • Value: Specifies the element's font family. It can be a generic font or a specific one, such as “Arial”, “Helvetica”, etc.
  1. Font size:
  • Property: font-size
  • Value: Defines the font size. It can be in pixels, em, rem, percentages, etc.
  1. Font style:
  • Property: font-style
  • Value: Can be “normal”, “italic” or “oblique”.
  1. Font thickness:
  • Property: font-weight
  • Value: Defines the thickness of the font. It can be “normal”, “bold”, numbers (for example, 400 for normal, 700 for bold).
  1. Line spacing:
  • Property: line-height
  • Value: Defines the vertical space between lines of text.
  1. Margins:
  • Property: Margin
  • Value: Defines the margins around the element. It can be a single value for all sides or four values for specific margins (up, right, down, left).
  1. Padding:
  • Property: Padding
  • Value: Defines the internal space around the content of an element.
  1. Borders:
  • Properties: border-width, Border-style, border-color
  • Values: Defines the width, style and color of an element's border.

body {
  color: #333; /* Color del texto en hexadecimal */
  background-color: #f4f4f4; /* Color de fondo en hexadecimal */
  font-family: 'Arial', sans-serif; /* Fuente principal con alternativa sans-serif */
  font-size: 16px; /* Tamaño de fuente en píxeles */
  font-style: italic; /* Estilo de la fuente: normal, italic, oblique, etc. */
  line-height: 1.5; /* Espaciado entre líneas, multiplicado por el tamaño de la fuente */
  margin: 20px; /* Márgenes externos de la página */
  padding: 10px; /* Relleno interno del contenido */
  border: 1px solid #ccc; /* Borde de 1 pĂ­xel sĂłlido con color en hexadecimal */
}


Box Model

The box model is essential for understanding how elements are structured and dimensioned in CSS.




Content

This is the area where the actual content of the element is displayed, such as text, images, or other nested HTML elements, such as paragraphs (<p>), headers (<h1>, <h2>, etc.), among others.

Padding

Space between the content and the border, this extra space is useful to improve the legibility and aesthetics of the page, as well as to ensure that the content is not too close to the edges of the element.


/* Establecer todos los padding a la vez */
.my-element {
   padding: 10px;
}

.my-element {
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
}


Border

It is the line that surrounds the content of an HTML element, and using the CSS property Border, you can easily customize its size, style and color, adjusting it to your design preferences.


.my-element {
    border: 1px solid red;
}


Margin:

The property Margin determines the space around an element. This space, known as the margin, can be customized for each of the four sides of the element: top, right, bottom, and left.


/* Establecer todos los márgenes a la vez */
.my-element {
    margin: 10px;
}

.my-element {
    margin-top: 10px;
    margin-right: 20px;
    margin-bottom: 10px;
    margin-left: 20px;
}


Margins aren't just limited to positive values; they're also They can be negative, which can be useful in certain design cases.




Positioning

  • static: This is the default position. The element follows the normal flow of the document.
  • related: It allows you to move an element from its normal position, without affecting other elements.
  • absolute: The element is positioned relative to its first positioned ancestor (that has no position). Static).
  • fixed: The element is positioned relative to the browser window.



Responsiveness

  • Media Queries: They allow you to apply styles based on the characteristics of the device, such as the width of the screen.

@media screen and (max-width: 600px) {
  body {
    font-size: 14px;
  }
}


  • ‍Relative Units: Use relative units as a percentage or In instead of absolute units so that the elements are adjusted proportionately to the screen size.



  • Flexbox and Grid: Flexible, grid-like design that makes it easy to create responsive interfaces.

.container {
  display: flex;
  justify-content: space-between;
}


Benefits of Using CSS:

  • CSS (Cascading Style Sheets) provides programmers with numerous advantages when developing applications, whether in desktop environments or mobile devices. Here are some of the key benefits:
  • Separation of Content and Presentation: CSS allows you to separate the HTML structure from the visual style. This improves the readability of the code, facilitates maintenance, and makes it easier to make changes to the design without affecting the structure of the content.
  • Reusing Styles: You can define styles in a CSS file and apply them to multiple web pages. This facilitates visual consistency across an entire website and reduces code duplication.
  • Ease of Maintenance: For example, by centralizing styles in CSS files, any design changes can be made efficiently and affect all pages that use that style. This simplifies the maintenance and upgrade process.
  • Accessibility: CSS provides tools to improve web accessibility, allowing developers to create pages that are more friendly to people with visual or other disabilities. For example, styles can be defined that improve the legibility of the text or that allow the use of screen readers.
  • Flexibility and Control: CSS provides a high degree of flexibility and control over the design of a web page. Developers can apply styles to specific elements, create responsive designs, and adapt to different devices and screen sizes.
  • Multiple Device Compatibility: Thanks to CSS's responsive design capabilities, it's possible to create websites that look good and work properly on a variety of devices, from desktops to tablets and mobile phones.
  • Maintaining Standards: CSS follows standards defined by the World Wide Web Consortium (W3C), which ensures consistency and compatibility between browsers. Using standards makes it easy to create websites that behave predictably in different environments.

CSS Project - Weather Widget:

  • To start our CSS exercise with HTML, the first step is to have a code editor. In my case, I'm using Visual Studio Code. Once we have the editor, we will proceed to create two files: one called index.html where we will store the HTML code of the project, and another one called style.css where we will develop the styles in CSS, in addition to creating a folder where we can store the images that will be used, as shown below.

In the HTML file, we'll start with the structure of the project. As an example, we will place the first card (Card) of the project, where we will store the main characteristics of the climate. We will include information such as the city to which we attribute the weather, wind speed, changes in rain and humidity, and the classes will be where we will attribute the classes that we will create in the style.css




In this CSS code, initially, the main font for the entire document is established using the rule applied to the selector Body. Subsequently, the selector Weather-container configure the background with an image and adjust general visual aspects. In addition, the current section (Current) presents a gradient background and specific styles for the text. Additional temperatures and details have specific sizes and colors.


body {
  font-family: Arial, Helvetica, sans-serif;
}

/*Estilo de los iconos*/
.material-icons {
  font-family: "Material Icons";
  font-weight: normal;
  font-style: normal;
  font-size: 24px; /* Puede cambiarse a rem, em, etc. */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;
}

.weather-container {
  background-image: url("/img/nuebes-sol.jpeg");
  background-size: cover;
  color: white;
  font-size: 18px;
  max-width: 450px;
  margin: 10px auto;
  background-color: #333;
  padding: 10px;
  border-radius: 50px;
}

.current {
  background: rgba(46, 112, 210, 0.46);
  background: linear-gradient(
    0deg,
    rgb(16, 99, 163) 0%,
    rgb(3, 150, 255) 42%,
    rgba(3, 200, 255, 0.466) 100%
  );
  border-radius: 40px;
  padding: 40px;
}
.city {
  text-align: center;
  font-weight: bold;
  font-size: 30px;
  margin-bottom: 10px;
}
.day {
  text-align: center;
}

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.info .temperature {
  font-size: 48px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.info .temperature .temperature-now {
  font-size: 70px;
  margin: 0;
}
.info .temperature .temperature-low {
  font-size: 32px;
  color: rgba(255, 255, 255, 0.7);
}
.status {
  color: rgba(255, 255, 255, 0.7);
}
.more {
  display: flex;
  justify-content: space-between;
  margin-top: 50px;
  gap: 10px;
  text-align: center;
}

.icon span {
  font-size: 28px;
  color: rgba(255, 255, 255, 0.7);
}
.text {
  font-weight: bold;
}
.type {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}


All the code presented is contained inside the div of Weather-container. In this second part of the HTML, the following days are defined along with the weather they will experience and the respective temperatures.




This section of the CSS code is dedicated to styling the list (List) of the weather widget, which presents the weather forecast for several days. In this specific part of the code, style rules are implemented to ensure responsive design through media queries (Media Query). This ensures that the presentation of the forecast is adequate and legible on different screen sizes, thus contributing to an improved user experience.


/* Segunda parte */
.list {
  padding: 50px 40px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.day-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.name {
  width: 123.3px;
  font-weight: bold;
}
.weather {
  width: 123px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.temperature {
  width: 123px;
  display: flow;
}

.temperature-low {
  color: rgba(255, 255, 255, 0.7);
}

@media only screen and (max-width: 450px) {
  .row {
    display: flex;
    flex-direction: column;
  }
  .list {
    padding: 50px 40px;
    gap: 20px;
  }

  .day-list {
    height: max-content;
    display: flex;
    flex-direction: column;
    background: rgba(46, 112, 210, 0.46);
    background: linear-gradient(
      0deg,
      rgba(16, 99, 163, 0.424) 0%,
      rgba(3, 150, 255, 0.541) 42%,
      rgba(3, 200, 255, 0.466) 100%
    );
    border-radius: 20px;
    padding: 10px;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.75);
  }

  .name {
    width: auto;
    margin-bottom: 0;
  }

  .weather {
    width: auto;
    flex-direction: row;
    align-items: center;
  }

  .temperature {
    width: auto;
    text-align: right;
  }
}


This is the final result of the project:

The full project is available at the following link in my GitHub repository:

https://github.com/karlacabanas01/widget-clima-css

References and tools for continuing to learn:

Ready to style your web projects with CSS?

At Kranio, we accompany you at every stage of your learning in web development. Our team of experts is ready to help you master CSS and other key technologies to create attractive and functional websites. Contact us and discover how we can boost your growth in the world of web development.

Karla Cabañas

September 16, 2024