Breaking News: Big Event Tomorrow
+Join us for our biggest event of the year!
+diff --git a/README.md b/README.md index db1f2cc..576540e 100644 --- a/README.md +++ b/README.md @@ -1,197 +1,733 @@ -
- You can check all - 50 - CSS interview questions here ๐ - https://devinterview.io/dev/css-interview-questions -
Using the inline style attribute on an element
<div>
- <p style="color: maroon;"></p>
-</div>
Using a <style>
block in the <head>
section of your HTML
<head>
- <title>CSS Refresher</title>
- <style>
- body {
- font-family: sans-serif;
- font-size: 1.2em;
- }
- </style>
-</head>
Loading an external CSS file using the <link>
tag
<head>
- <title>CSS Refresher</title>
- <link rel="stylesheet" href="/css/styles.css" />
-</head>
CSS stands for Cascading Style Sheets. CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.
CSS was intended to allow web professionals to separate the content and structure of a website's code from the visual design.
Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can store things like colors, font stacks, or any CSS value you think you'll want to reuse. Sass uses the $
symbol to make something a variable.
$font-stack: Helvetica, sans-serif;
-$primary-color: #333;
-
-body {
- font: 100% $font-stack;
- color: $primary-color;
-}
CSS sprites combine multiple images into one single larger image. It is commonly used technique for icons (Gmail uses it).
background-image
, background-position
and background-size
properties defined.Advantages:
:hover
pseudo-states. Blinking wouldn't be seen.The CSS box model is a rectangular layout paradigm for HTML elements that consists of the following:
Web browsers apply CSS rules to a document to affect how they are displayed. A CSS rule is formed from:
A set of CSS rules contained within a stylesheet determines how a webpage should look.
Using @extend
lets you share a set of CSS properties from one selector to another. It helps keep your Sass very dry.
Consider:
%message-shared {
- border: 1px solid #ccc;
- padding: 10px;
- color: #333;
-}
-
-.message {
- @extend %message-shared;
-}
-
-.success {
- @extend %message-shared;
- border-color: green;
-}
-
-.error {
- @extend %message-shared;
- border-color: red;
-}
-
-.warning {
- @extend %message-shared;
- border-color: yellow;
-}
CSS output:
.message, .success, .error, .warning {
- border: 1px solid #cccccc;
- padding: 10px;
- color: #333;
-}
-
-.success {
- border-color: green;
-}
-
-.error {
- border-color: red;
-}
-
-.warning {
- border-color: yellow;
-}
Yes. Flexbox is mainly meant for 1-dimensional layouts while Grid is meant for 2-dimensional layouts.
Flexbox solves many common problems in CSS, such as vertical centering of elements within a container, sticky footer, etc. Bootstrap and Bulma are based on Flexbox, and it is probably the recommended way to create layouts these days. Have tried Flexbox before but ran into some browser incompatibility issues (Safari) in using flex-grow
, and I had to rewrite my code using inline-blocks
and math to calculate the widths in percentages, it wasn't a nice experience.
Grid is by far the most intuitive approach for creating grid-based layouts (it better be!) but browser support is not wide at the moment.
The Document Object Model (DOM) is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure wherein each node is an object representing a part of the document.
With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. The DOM specifies interfaces which may be used to manage XML or HTML documents.
When a browser displays a document, it must combine the document's content with its style information. The browser converts HTML and CSS into the DOM (Document Object Model). The DOM represents the document in the computer's memory. It combines the document's content with its style.
Sass or Syntactically Awesome StyleSheets is a CSS preprocessor that adds power and elegance to the basic language. It allows you to use variables, nested rules, mixins, inline imports, and more, all with a fully CSS-compatible syntax. Sass helps keep large stylesheets well-organized, and get small stylesheets up and running quickly.
A CSS preprocessor is a scripting language that extends CSS by allowing developers to write code in one language and then compile it into CSS.
Float is a CSS positioning property. Floated elements remain a part of the flow of the web page. This is distinctly different than page elements that use absolute positioning. Absolutely positioned page elements are removed from the flow of the webpage.
#sidebar {
- float: right; // left right none inherit
-}
The CSS clear property can be used to be positioned below left
/right
/both
floated elements.
Sass let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. CSS, on the other hand, doesn't have any visual hierarchy.
Consider example (scss):
.parent {
- color: red;
-
- .child {
- color: blue;
- }
-}
Result (css):
.parent {
- color: red;
-}
-
-.parent .child {
- color: blue;
-}
Key features for Sass include
IDsโโโMeant to be unique within the document. Can be used to identify an element when linking using a fragment identifier. Elements can only have one id attribute.
ClassesโโโCan be reused on multiple elements within the document. Mainly for styling and targeting elements.
Sass supports seven main data types:
$size: 18; // A number
-$px-unit: $size * 1px; // A pixel measurement
-$px-string: $size + px; // A string
-$px-number: $px-unit / 1px; // A number
$website: 'SitePoint'; // Stores SitePoint
-$name: 'Gajendar' + ' Singh'; // 'Gajendar Singh'
-$date: 'Month/Year : ' + 3/2016; // 'Month/Year : 3/2016'
-$date: 'Month/Year : ' + (3/2016); // 'Month/Year : 0.00149'
-// This is because 3/2016 is evaluated first.
-$variable: 3/2016; // Evaluated to 0.00149
color
data type. You can refer to the colors in hexadecimal notation, as rgb
, rgba
, hsl
and hsla
values or use native keywords like pink
, blue
, etc. $color: yellowgreen; // #9ACD32
-color: lighten($color, 15%); // #b8dc70
-color: darken($color, 15%); // #6c9023
-color: saturate($color, 15%); // #a1e01f
-color: desaturate($color, 15%); // #93ba45
-color: (green + red); // #ff8000
true
and false
$i-am-true: true;
-
-body {
- @if not $i-am-true {
- background: rgba(255, 0, 0, 0.6);
- } @else {
- background: rgba(0, 0, 255, 0.6); // expected
- }
-}
true
or false
. This is typically the value you want to set when defining a variable without a value, only to prevent the parser from crashing..foo {
- content: type-of(null); // null
- content: type-of(NULL); // string
- $bar: 'foo' + null; // invalid null operation: "foo plus nullโ.
-}
$font-list: 'Raleway','Dosis','Lato'; // Three comma separated elements
-$pad-list: 10px 8px 12px; // Three space separated elements
-$multi-list: 'Roboto',15px 1.3em; // This multi-list has two lists.
$styling: (
- 'font-family': 'Lato',
- 'font-size': 1.5em,
- 'color': tomato,
- 'background': black
-);
-
-h1 {
- color: map-get($styling, 'color');
- background: map-get($styling, 'background');
-}
If you want to use variables inside a string, you will have to use a process called variable interpolation. To use it you will have to wrap your variables in #{}
.
Consider:
$name: 'Gajendar';
-$author: 'Author : $name'; // 'Author : $name'
-
-$author: 'Author : #{$name}';
-// 'Author : Gajendar'
The interpolation method could be useful in situations where the value of a variable is determined by some conditional statements.
There are two syntaxes available for Sass. The first, known as SCSS (Sassy CSS) and used throughout this reference, is an extension of the syntax of CSS. This means that every valid CSS stylesheet is a valid SCSS file with the same meaning. This syntax is enhanced with the Sass features described below. Files using this syntax have the .scss
extension.
The second and older syntax, known as the indented syntax (or sometimes just Sass), provides a more concise way of writing CSS. It uses indentation rather than brackets to indicate nesting of selectors, and newlines rather than semicolons to separate properties. Files using this syntax have the .sass
extension.
Consider example.sass:
$color: red
-
-=my-border($color)
- border: 1px solid $color
-
-body
- background: $color
- +my-border(green)
Consider example.scss:
$color: red;
-
-@mixin my-border($color) {
- border: 1px solid $color;
-}
-
-body {
- background: $color;
- @include my-border(green);
-}
The table-layout
property defines the algorithm used to lay out table cells, rows, and columns.
table-layout: auto|fixed|initial|inherit;
A positioned element is an element whose computed position
property is either relative
, absolute
, fixed
or sticky
.
static
- The default position; the element will flow into the page as it normally would. The top
, right
, bottom
, left
and z-index
properties do not apply.relative
- The element's position is adjusted relative to itself, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).absolute
- The element is removed from the flow of the page and positioned at a specified position relative to its closest positioned ancestor if any, or otherwise relative to the initial containing block. Absolutely positioned boxes can have margins, and they do not collapse with any other margins. These elements do not affect the position of other elements.fixed
- The element is removed from the flow of the page and positioned at a specified position relative to the viewport and doesn't move when scrolled.sticky
- Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative
positioned until it crosses a specified threshold, at which point it is treated as fixed
positioned.Retina is just a marketing term to refer to high resolution screens with a pixel ratio bigger than 1. The key thing to know is that using a pixel ratio means these displays are emulating a lower resolution screen in order to show elements with the same size. Nowadays we consider all mobile devices retina defacto displays.
Browsers by default render DOM elements according to the device resolution, except for images.
In order to have crisp, good-looking graphics that make the best of retina displays we need to use high resolution images whenever possible. However using always the highest resolution images will have an impact on performance as more bytes will need to be sent over the wire.
To overcome this problem, we can use responsive images, as specified in HTML5. It requires making available different resolution files of the same image to the browser and let it decide which image is best, using the html attribute srcset
and optionally sizes
, for instance:
<div responsive-background-image>
- <img src="/images/test-1600.jpg"
- sizes="
- (min-width: 768px) 50vw,
- (min-width: 1024px) 66vw,
- 100vw"
- srcset="
- /images/test-400.jpg 400w,
- /images/test-800.jpg 800w,
- /images/test-1200.jpg 1200w">
-</div>
It is important to note that browsers which don't support HTML5's srcset
(i.e. IE11) will ignore it and use src
instead. If we really need to support IE11 and we want to provide this feature for performance reasons, we can use a JavaScript polyfill, e.g. Picturefill (link in the references).
For icons, I would also opt to use SVGs and icon fonts where possible, as they render very crisply regardless of resolution.
Advantages:
Disadvantages:
Both responsive and adaptive design attempt to optimize the user experience across different devices, adjusting for different viewport sizes, resolutions, usage contexts, control mechanisms, and so on.
Responsive design works on the principle of flexibilityโโโa single fluid website that can look good on any device. Responsive websites use media queries, flexible grids, and responsive images to create a user experience that flexes and changes based on a multitude of factors. Like a single ball growing or shrinking to fit through several different hoops.
Adaptive design is more like the modern definition of progressive enhancement. Instead of one flexible design, adaptive design detects the device and other features, and then provides the appropriate feature and layout based on a predefined set of viewport sizes and other characteristics. The site detects the type of device used, and delivers the pre-set layout for that device. Instead of a single ball going through several different-sized hoops, youโd have several different balls to use depending on the hoop size.
A CSS selector is the part of a CSS rule set that actually selects the content you want to style.
Consider some types of CSS selectors:
*
ul
, td
#id
.box
#id .box
. The .box element doesnโt have to be an immediate child of #id.#id > .box
. Unlike the descendant combinator, there canโt be another element wrapping .box~
+
. The difference from general sibling combinaltor is that the targeted element must be an immediate sibling, not just a general sibling.input[type="text"]
a:hover
. A pseudo-class uses a colon character to identify a pseudo-state that an element might be in..container::before
. This selector inserts an imaginary element into the page, inside the targeted element, before its contents.Accessibility (a11y) is a measure of a computer system's accessibility is to all people, including those with disabilities or impairments. It concerns both software and hardware and how they are configured in order to enable a disabled or impaired person to use that computer system successfully.
Accessibility is also known as assistive technology.
A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own unique syntax. There are many CSS preprocessors to choose from, however most CSS preprocessors will add some features that don't exist in pure CSS, such as mixin, nesting selector, inheritance selector, and so on. These features make the CSS structure more readable and easier to maintain.
Here are a few of the most popular CSS preprocessors:
autoprefixer
to automatically add vendor prefixes to your code.margins
, paddings
, font-sizes
of all elements are reset to be the same. You will have to redeclare styling for common typographic elements.It's a good idea to choose resetting when you have very a customized or unconventional site design such that I need to do a lot of my own styling do not need any default styling to be preserved.
The CSS box model is responsible for calculating:
div {
- width: 300px;
- border: 25px solid green;
- padding: 25px;
- margin: 25px;
-}
The box model has the following rules:
width
, height
, padding
, borders
, and margins
.block
element will be as high as the content it contains, plus padding (unless there are floats, for which see below).block
element will expand to fit the width of its parent minus padding.height
of an element is calculated by the content's height.width
of an element is calculated by the content's width.paddings
and borders
are not part of the width and height of an element.A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). They can be used for decoration (:first-line
, :first-letter
) or adding elements to the markup (combined with content: ...
) without having to modify the markup (:before
, :after
).
Example of usage:
:first-line
and :first-letter
can be used to decorate text..clearfix
hack to add a zero-space element with clear: both
.:before
and :after
. Encourages separation of concerns because the triangle is considered part of styling and not really the DOM, but not really possible to draw a triangle with just CSS styles.
+
+
+
+
Join us for our biggest event of the year!
+Hello, World!
+ + +``` +`). + +- **ID Selector** (`#idName{...}`): Identifies a **single unique element** based on its unique ID attribute. While it's still possible to style multiple elements with the same ID, best practices mandate unique IDs for effective CSS usage. + +### Efficiency and Performance + +- **Class Selector**: Generally faster to compute than ID selectors in modern browsers, particularly when applied to a large number of elements. + +- **ID Selector**: Formerly superior in terms of speed, contemporary browsers mitigate this difference. + +### Common Use Cases + +- **Class Selector**: Ideal for styling groups of elements based on shared attributes or type. + +- **ID Selector**: Typically reserved for unique elements that require highly specific styling or JavaScript manipulation. While it's valid to use an ID for styling, as stated in the HTML5 specification, it's generally more maintainable to reserve the use of IDs for uniquely identifiable elements and use classes for styling. + +### Code Example: Class and ID Selectors + +Here is the HTML code: + +```html + +
+ + + +Paragraph 1
+Paragraph 1
+Paragraph 2
+This is paragraph 1
+This is paragraph 2
+