Interview - CSS

How to center a div without using flex or grid ?

<html lang="en">
  <head>
    <style>
      html, body{
        margin: 0;
        width: 100%;
        height: 100%;
        display: table;
        text-align: center;
      }
      
      .container{
        display: table-cell;
        vertical-align: middle;
      }
    </style>
  </head>
  <body>        
    <div class="container">
      div
    </div> 
  </body>
</html>

What is the box model ?

In CSS, the term box model is used when talking about design and layout.


The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.


Explanation of the different parts:


  • Content - The content of the box, where text and images appear.
  • Padding - Clears an area around the content. The padding is transparent.
  • Border - A border that goes around the padding and content.
  • Margin - Clears an area outside the border. The margin is transparent.


The box model allows us to add a border around elements, and to define space between elements.


In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.


Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.


The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin


The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin





What is the difference between a class and an ID ?

id

The id attribute is a unique identifier that is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is written using the # symbol followed by id.


class

The class attribute is used to specify one or more class names for an HTML element. The class attribute can be used on any HTML element. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. The class name in CSS stylesheet using . symbol.


Difference between id and class attribute: The only difference between them is that id is unique in a page and can only apply to at most one element, while class selector can apply to multiple elements.