30 Basic Git Commands You Should Know

When it comes to software development, version control is essential. It allows you to track your code changes, revert to previous stages, and collaborate with your team on a project. One of the most popular version control systems is Git. Whether you’re a beginner just starting out or an experienced developer looking to streamline your workflow, understanding Git commands is a skill that will undoubtedly pay off.

basic git commands

In this post, we will delve into 30 basic Git commands that every developer should know. These commands will help you initialize a repository, make commits, create and switch branches, and much more. By mastering these commands, you’ll be well on your way to becoming a more efficient and effective developer.

10 Useful Github Features to Know

10 Useful Github Features to Know

Github is now the place where programmers and designers work together. They collaborate, contribute, and fix bugs. It… Read more

1. git init:

This command is used to initialize a new Git repository. It creates a new .git subdirectory in your current working directory. This will also create a new branch named master.

Example:

git init

This will initialize a Git repository in your current directory.

2. git clone:

This command is used to clone a repository. It creates a copy of a remote repository on your local machine.

Example:

git clone https://github.com/username/repository.git

This will clone the repository at the given URL to your local machine.

3. git add:

This command adds a file to the staging area in preparation for a commit.

Example:

git add filename

This will add the file named “filename” to the staging area.

4. git commit:

This command is used to save your changes to the local repository. It takes a snapshot of the changes you’ve staged using git add.

Example:

git commit -m "Commit message"

This will commit your changes with a message describing what you changed.

5. git status:

This command shows the status of changes as untracked, modified, or staged.

Example:

git status

This will display the status of your working directory.

6. git pull:

This command fetches changes from a remote repository and merges them into your current branch.

Example:

git pull origin master 

This will pull changes from the master branch of the origin remote repository.

7. git push:

This command sends your committed changes to a remote repository.

Example:

git push origin master 

This will push your committed changes to the master branch of the origin remote repository.

8. git branch:

This command lists all of the branches in your repository.

Example:

git branch

This will list all of the branches in your repository.

9. git checkout:

This command is used to switch between branches in a Git repository.

Example:

git checkout branch-name

This will switch to the branch named “branch-name”.

10. git merge:

This command merges the changes from one branch into another.

Example:

git merge branch-name
11. git diff:

This command shows the file differences which are not yet staged.

Example:

git diff 

This will show unstaged differences since the last commit.

12. git reset:

This command unstages the file, but it preserves the file contents.

Example:

git reset filename 

This will unstage the file named “filename“.

13. git rm:

This command deletes the file from your working directory and stages the deletion.

Example:

git rm filename

This will delete the file named “filename” and stage the deletion.

14. git log:

This command shows a listing of commits on a branch including the corresponding details.

Example:

git log 

This will display an ordered list of the recent commits.

15. git show:

This command shows the metadata and content changes of the specified commit.

Example:

git show

This will display the metadata and content changes of the latest commit.

16. git tag:

This command is used to give tags to the specified commit.

Example:

git tag v1.0

This will tag the latest commit with “v1.0”.

17. git fetch:

This command fetches all the objects from the remote repository that are not present in the local one.

Example:

git fetch origin

This will fetch all objects from the origin remote that don’t exist in your current repository.

18. git rebase:

This command is used to apply the changes made on the current branch ahead of another branch.

Example:

git rebase master

This will apply any changes made on the current branch ahead of the master branch.

19. git revert:

This command creates a new commit that undoes the changes made in a previous commit.

Example:

git revert HEAD

This will create a new commit that undoes the changes made in the last commit.

20. git stash:

This command temporarily saves changes that you don’t want to commit immediately. You can apply the changes later.

Example:

git stash 

This will temporarily save all modified tracked files.

21. git stash pop:

This command restores the most recently stashed changes.

Example:

git stash pop

This will apply the most recently stashed changes and remove them from the stash list.

22. git stash list:

This command lists all stashed changesets.

Example:

git stash list 

This will display all stashed changesets.

23. git stash drop:

This command discards the most recently stashed changeset.

Example:

git stash drop

This will discard the most recently stashed changeset.

24. git cherry-pick:

This command applies the changes introduced by some existing commits.

Example:

git cherry-pick commitID 

This will apply the changes introduced by the commit with the given ID.

25. git bisect:

This command uses a binary search algorithm to find which commit in your project’s history introduced a bug.

Example:

git bisect start
git bisect bad
git bisect good commitID

This will start the bisecting process, mark the current commit as bad, and mark the commit with the given ID as good.

26 git blame:

This command shows what revision and author last modified each line of a file.

Example:

git blame filename 

This will show what revision and author last modified each line of “filename”.

27. git clean:

This command removes untracked files from your working directory.

Example:

git clean -n 

This will show what will be removed without actually doing it. Replace -n with -f to actually remove the files.

28 git reflog:

This command shows a list of all references to commits in the local repository.

Example:

git reflog 

This will display all references to commits in your local repository.

29. git grep:

This command lets you search through your repository.

Example:

git grep "hello" 

This will search the repository for any occurrences of “hello”.

30. gitk:

This command launches the Git repository browser.

Example:

gitk

This will launch the Git repository browser.

Conclusion

In conclusion, Git is a powerful tool that can greatly enhance your productivity and efficiency as a developer. The 30 basic Git commands we’ve discussed in this post are just the tip of the iceberg. There are many more commands and options available in Git, and we encourage you to explore them further.

Remember, practice makes perfect. The more you use these commands, the more comfortable you’ll become with them. So, don’t be afraid to dive in and start using Git in your projects. It may seem daunting at first, but with time and practice, you’ll find that it’s an invaluable tool in your development toolkit.

The post 30 Basic Git Commands You Should Know appeared first on Hongkiat.

10 Common CSS Mistakes Developers Often Make

CSS is a powerful tool that brings our websites to life. It’s the magic behind the beautiful, interactive, and responsive designs that captivate users. However, like any tool, it’s not immune to misuse or misunderstanding. Even the most seasoned developers can fall into common CSS pitfalls that can turn a dream website into a nightmare of bugs and inconsistencies.

CSS coding

In this blog post, we’ll shine a light on the ten common CSS mistakes developers make; whether you’re a beginner just dipping your toes into the CSS pool, or an experienced developer looking to brush up on best practices, this post is for you.

By understanding and avoiding these common CSS mistakes, you can write cleaner, more efficient code, ensure your websites look and function as intended across all browsers and devices, and ultimately provide a better user experience.

1. Not Using a Reset CSS

Different browsers have different default styles for elements. For example, the default margin and padding for the <body> element might be different in Chrome and Firefox. This can lead to inconsistencies in how your website looks across different browsers.

Example:

Let’s say you have a simple HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
</head>
<body>
    <h1>Hello, world!</h1>
</body>

And you have some CSS:

body {
    margin: 0;
    padding: 0;
}

h1 {
    margin: 0;
    padding: 0;
}

Even with this CSS, the <h1> might still have some margin in some browsers, because they have a default style for <h1> that includes a margin.

Fix:

To fix this issue, you can use a reset CSS. A reset CSS is a set of styles that you apply at the beginning of your CSS file to reset the default styles of elements. Here’s a simple reset CSS:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

This CSS resets the margin and padding of all elements to 0, and sets their box-sizing to border-box. This can help eliminate inconsistencies between browsers.

However, this is a very simple reset and might not cover all elements and styles. There are more comprehensive reset CSS files available, like the Meyer’s reset, which you can find online and use in your projects.

Using a reset CSS can make your website look very plain, because it removes all default styles. After applying a reset, you’ll need to style all elements yourself. But this gives you complete control over the look of your website.

2. Not Using Shorthand Properties

CSS has shorthand properties that allow you to set multiple related styles at once. If you’re not using them, your CSS can become unnecessarily long and harder to maintain.

Example:

Let’s say you have the following CSS:

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

This CSS applies margin to all four sides of elements with the class “box“. But it’s quite verbose.

Fix:

You can use the shorthand margin property to set all four margins at once:

.box {
    margin: 10px 20px;
}

This does the same thing as the previous CSS. The first value is the top and bottom margin, and the second value is the right and left margin.

Here’s another example with the background property. Instead of this:

.box {
    background-color: #000;
    background-image: url('image.jpg');
    background-repeat: no-repeat;
    background-position: center;
}

You can write this:

.box {
    background: #000 url('image.jpg') no-repeat center;
}

Shorthand properties can make your CSS much shorter and easier to read and maintain. They can also help ensure consistency in your styles.

However, be aware that when you use a shorthand property, any unspecified sub-properties are set to their initial values. For example, if you use the background shorthand property and don’t specify a background size, the background size is set to its default value of “auto“.

3. Using Inline Styles

Inline styles are CSS declarations that are applied directly within your HTML elements. While they might seem convenient for quick styling, they can lead to several issues:

Maintenance Difficulty: If you have a large HTML file with many elements using inline styles, it can become very difficult to maintain and update your styles.

Specificity Issues: Inline styles have a very high specificity. This means that they will override any styles declared in your external or internal CSS, making it difficult to override them when needed.

Reusability: Inline styles are not reusable. If you want to apply the same styles to multiple elements, you would have to repeat the inline styles for each element.

Example:

Here’s an example of an inline style:

<h1 style="color: blue; font-size: 2em;">Hello, world!</h1>
Fix:

Instead of using inline styles, it’s better to use external or internal CSS. Here’s how you can do the same thing with internal CSS:

<head>
    <style>
        .blue-heading {
            color: blue;
            font-size: 2em;
        }
    </style>
</head>
<body>
    <h1 class="blue-heading">Hello, world!</h1>
</body>

And here’s how you can do it with external CSS. First, create a CSS file (let’s call it “styles.css”):

.blue-heading {
    color: blue;
    font-size: 2em;
}

Then, link it in your HTML file:

<head>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1 class="blue-heading">Hello, world!</h1>
</body>

Using external or internal CSS makes your styles easier to maintain and update, allows you to reuse styles, and avoids specificity issues. It’s a best practice to avoid using inline styles whenever possible.

4. Not Using Vendor Prefixes

Vendor prefixes are a way for browser makers to add new CSS features before they become part of the official CSS specifications. Not using them can lead to some CSS properties not being recognized by some browsers, causing inconsistencies in your design.

Example:

Let’s say you want to use the box-shadow property, which is a relatively new addition to CSS:

.box {
    box-shadow: 10px 10px 5px #888888;
}

This CSS will work in most modern browsers, but older versions of some browsers might not recognize the box-shadow property.

Fix:

To ensure that your CSS works in as many browsers as possible, you can use vendor prefixes. Here’s how you can add a box shadow with vendor prefixes:

.box {
    -webkit-box-shadow: 10px 10px 5px #888888; /* Safari and Chrome */
    -moz-box-shadow: 10px 10px 5px #888888; /* Firefox */
    box-shadow: 10px 10px 5px #888888; /* non-prefixed, works in most modern browsers */
}

This CSS will apply a box shadow in Safari, Chrome, Firefox, and most other modern browsers.

However, keep in mind that vendor prefixes should be used as a last resort. The use of vendor prefixes can lead to bloated and hard-to-maintain code. It’s better to write standard CSS and let tools like Autoprefixer add the vendor prefixes for you.

Also, note that as CSS evolves and browsers update, the need for vendor prefixes decreases. Many properties that once required vendor prefixes now are universally supported without them. Always check the current browser compatibility for a CSS feature before deciding to use vendor prefixes.

5. Using Too Specific Selectors

In CSS, specificity determines which CSS rule is applied by the browsers. If your selectors are too specific, it can make your CSS hard to override and maintain. It can also lead to unnecessary complexity in your CSS.

Example:

Let’s say you have the following CSS:

body div#container ul.nav li a {
    color: blue;
}

This selector is very specific. It selects an <a> element that is a descendant of an <li> element, which is a descendant of a <ul> with a class of “nav”, which is a descendant of a <div> with an ID of “container”, which is a descendant of the <body>.

Fix:

It’s better to use classes and keep your selectors as simple as possible. Here’s how you can simplify the previous selector:

.nav a {
    color: blue;
}

This selector does the same thing as the previous one, but it’s much simpler. It selects any <a> element that is a descendant of an element with a class of “nav”.

Simplifying your selectors makes your CSS easier to read and maintain. It also reduces the likelihood of specificity conflicts, where more specific selectors override less specific ones.

However, be aware that simplifying your selectors can also increase the likelihood of naming conflicts, where two elements have the same class name but should have different styles. To avoid this, you can use methodologies like BEM (Block, Element, Modifier) to name your classes in a way that reduces the likelihood of conflicts.

6. Not Organizing Your CSS

If your CSS is not organized, it can be hard to find and change styles. This can lead to difficulties in maintaining your code, especially when working with large stylesheets or in a team environment.

Example:

Let’s say you have a CSS file with hundreds of lines of code, and the styles are all mixed up:

h1 {
    color: blue;
}

.footer {
    background: black;
}

h2 {
    color: green;
}

.header {
    background: white;
}

In this example, the styles for different sections of the website are scattered throughout the CSS file. This can make it hard to find the styles for a specific section when you need to update them.

Fix:

A good practice is to organize your CSS in a logical way. Here’s how you can organize the previous CSS:

/* Header */
.header {
    background: white;
}

h1 {
    color: blue;
}

h2 {
    color: green;
}

/* Footer */
.footer {
    background: black;
}

In this example, the styles are grouped by the section of the website they apply to. This makes it easier to find and update the styles for a specific section.

There are many ways to organize your CSS, and the best method depends on the specifics of your project. Some developers prefer to organize their CSS by component, others prefer to organize it by page, and others prefer to organize it by type of style (typography, layout, color, etc.).

In addition to organizing your CSS within each file, it’s also a good idea to organize your CSS files themselves. For large projects, it can be helpful to split your CSS into multiple files (for example, one for typography, one for layout, one for colors, etc.) and then import them all into a main stylesheet using @import statements. This can make your CSS easier to manage and maintain.

7. Not Using CSS Variables

CSS variables, also known as custom properties, allow you to store specific values for reuse throughout your CSS. If you’re not using them, you might find yourself repeating the same values over and over, which can make your CSS harder to maintain and update.

Example:

Let’s say you have a specific shade of blue that you use frequently in your CSS:

.header {
    background-color: #007BFF;
}

.button {
    background-color: #007BFF;
}

.link {
    color: #007BFF;
}

In this example, the same color value is repeated three times. If you decide to change this color, you would have to find and update every instance of it in your CSS.

Fix:

You can use a CSS variable to store this color value:

:root {
    --main-color: #007BFF;
}

.header {
    background-color: var(--main-color);
}

.button {
    background-color: var(--main-color);
}

.link {
    color: var(--main-color);
}

In this example, the color value is stored in a variable called --main-color, and this variable is used wherever the color is needed. If you decide to change this color, you only need to update the variable, and the change will be applied everywhere the variable is used.

CSS variables can make your CSS easier to maintain and update. They can also help ensure consistency in your styles. However, be aware that CSS variables are not supported in some older browsers, so if you need to support this browser, you might need to provide a fallback or use a preprocessor like Sass or Less, which have their own systems for variables.

8. Not Considering Accessibility

Accessibility in web design means making your website usable for all people, regardless of their abilities or disabilities. This includes people with visual, auditory, cognitive, and motor impairments. If you’re not considering accessibility in your CSS, you might be excluding a significant portion of your audience.

Example:

Let’s say you have a website with light gray text on a white background:

body {
    color: #999;
    background-color: #fff;
}

This might look stylish, but it’s hard to read for people with low vision or color vision deficiencies.

Fix:

To make your website more accessible, you can use high contrast colors for your text and background:

body {
    color: #333;
    background-color: #fff;
}

This is much easier to read, even for people with vision impairments.

In addition to color contrast, there are many other aspects of accessibility to consider in your CSS. Here are a few examples:

  • Use relative units like em and rem for font sizes, so users can adjust the text size if needed.
  • Avoid using CSS to hide content that should be accessible to screen readers. For example, use visibility: hidden or opacity: 0 instead of display: none.
  • Use media queries to make your design responsive, so it’s usable on all screen sizes.
  • Use ARIA roles and properties when necessary to provide additional information to assistive technologies.

Remember, accessibility is not just a nice-to-have feature, it’s a requirement for good web design. Making your website accessible can improve its usability for all users, not just those with disabilities.

9. Not Testing on Multiple Browsers

Your website can look and behave differently on different browsers due to differences in how they interpret and render CSS. If you’re not testing your website on all major browsers, you might be unaware of these differences, leading to a poor user experience for some of your visitors.

Example:

Let’s say you’ve used the CSS grid layout in your website design:

.container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
}

While CSS Grid is supported in all modern browsers, it may not be fully supported or may behave differently in older versions of some browsers.

Fix:

To ensure your website looks and works correctly on all major browsers, you should test it on each one. This includes Chrome, Firefox, Safari, and Edge. There are also tools available that can help you with cross-browser testing, such as BrowserStack and BitBar.

If you find that a certain CSS feature is not supported or behaves differently in a certain browser, you can use feature queries (@supports rule) to provide a fallback:

.container {
    display: flex;
}

@supports (display: grid) {
    .container {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
    }
}

In this example, the container will use the flex layout by default. If the browser supports CSS Grid (as determined by the @supports rule), it will use the grid layout instead.

The goal of cross-browser testing is not to make your website look exactly the same on all browsers, but to ensure a consistent and usable experience for all users.

10. Not Using Responsive Design

With the variety of devices and screen sizes today, it’s important to make your website responsive. This means that the layout and design of your website should adapt to the screen size of the device it’s being viewed on. If you’re not using responsive design, your website might be hard to use on some devices, particularly mobile devices.

Example:

Let’s say you have a website with a fixed width:

.container {
    width: 1200px;
}

This website will look fine on screens that are 1200px wide or larger, but on smaller screens, it will cause horizontal scrolling, which is generally considered a poor user experience.

Fix:

To make your website responsive, you can use media queries to apply different styles for different screen sizes. Here’s how you can make the previous example responsive:

.container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}

In this example, the container will take up 100% of the screen width on smaller screens, and it will be centered with a maximum width of 1200px on larger screens.

You can also use media queries to apply completely different styles for different screen sizes. For example:

.container {
    width: 100%;
}

@media (min-width: 768px) {
    .container {
        width: 750px;
        margin: 0 auto;
    }
}

@media (min-width: 1200px) {
    .container {
        width: 1170px;
        margin: 0 auto;
    }
}

In this example, the container will be full width on screens smaller than 768px, 750px wide on screens between 768px and 1199px, and 1170px wide on screens that are 1200px or larger.

Using responsive design can make your website more user-friendly and accessible to a wider audience. It’s a crucial aspect of modern web design.

The post 10 Common CSS Mistakes Developers Often Make appeared first on Hongkiat.

Understand Units in CSS: A Comprehensive Guide

CSS (Cascading Style Sheets) is a crucial component of modern web design. It’s the language that gives your website its look and feel. But to truly master CSS, you need to understand the units it uses to measure things like length, angle, time, and resolution.

CSS units

In this guide, we take a look into each type of CSS unit, providing an explanations and practical examples to help you grasp their usage. We’ll cover everything from absolute and relative length units like px, em, rem, and viewport units like vw, vh, to more specialized units like degrees deg for rotation, seconds s and milliseconds ms for animation durations, and even dots per inch dpi for resolution.

By understanding these CSS units, you’ll gain more control over your layouts, leading to more precise, responsive, and visually appealing designs.

1. Absolute Lengths

px (Pixels)

This is the most commonly used unit in web design. A pixel represents a single point on a computer screen.

Example: font-size: 16px; sets the font size to 16 pixels.

cm (Centimeters)

This unit is not commonly used in web design because screen sizes and resolutions vary greatly between devices. However, it can be useful for print media.

Example: width: 10cm; sets the width of an element to 10 centimeters.

mm (Millimeters)

Similar to centimeters, millimeters are not commonly used in web design but can be useful for print media.

Example: width: 100mm; sets the width of an element to 100 millimeters.

in (Inches)

This unit is also more useful for print media than web design.

Example: width: 4in; sets the width of an element to 4 inches.

pt (Points)

Points are traditionally used in print media (1 point is equal to 1/72 of an inch). In CSS, points are useful for creating styles that can be printed with precision.

Example: font-size: 12pt; sets the font size to 12 points.

pc (Picas)

A pica is equal to 12 points. It’s another unit that’s more commonly used in print than in web design.

Example: font-size: 1pc; sets the font size to 12 points.

Absolute length in CSS:

Here’s an example of how these units might be used in a CSS rule:

div {
    width: 300px;
    height: 20cm;
    padding: 5mm;
    border: 1in solid black;
    font-size: 14pt;
    margin: 1pc;
}

Code explanation:

The div element would have a width of 300 pixels, a height of 20 centimeters, padding of 5 millimeters, a border that’s 1 inch wide, a font size of 14 points, and a margin of 1 pica.

However, keep in mind that these units may render differently on different screens and devices due to varying pixel densities and screen sizes.

2. Relative Lengths

em

This unit is relative to the font-size of the element.

Example: If an element has a font-size of 16px, then 1em = 16px for that element. If you set margin: 2em;, the margin will be twice the current font size.

rem

This unit is relative to the font-size of the root element (usually the <html> element). If the root element has a font-size of 20px, then 1rem = 20px for any element on the page.

Example: font-size: 1.5rem; will set the font size to 1.5 times the font size of the root element.

ex

This unit is relative to the x-height of the current font (roughly the height of lowercase letters). It’s not commonly used.

ch

This unit is equal to the width of the “0” (zero) of the current font.

Example: width: 20ch; will make an element 20 “0” characters wide.

vw (Viewport Width)

This unit is equal to 1% of the width of the viewport.

Example: width: 50vw; will make an element 50% as wide as the viewport.

vh (Viewport Height)

This unit is equal to 1% of the height of the viewport.

Example: height: 70vh; will make an element 70% as tall as the viewport.

vmin

This unit is equal to 1% of the smaller dimension (width or height) of the viewport.

Example: font-size: 4vmin; will set the font size to 4% of the viewport’s smaller dimension.

vmax

This unit is equal to 1% of the larger dimension (width or height) of the viewport.

Example: font-size: 4vmax; will set the font size to 4% of the viewport’s larger dimension.

%

This unit is relative to the parent element.

Example: If you set width: 50%;, the element will take up half the width of its parent element.

Relative length in CSS:

Here’s an example of how these units might be used in a CSS rule:

div {
    font-size: 2em;
    padding: 1.5rem;
    width: 75vw;
    height: 50vh;
    margin: 5vmin;
    line-height: 200%;
}

Explaination:

The div element would have a font size twice that of its parent, padding 1.5 times the root font size, width 75% of the viewport width, height 50% of the viewport height, and a margin of 5% of the viewport’s smaller dimension. The line height is 200% of the current font size.

3. Time Units

s (Seconds)

This unit represents a time duration in seconds. It’s commonly used with animation and transition properties.

Example: animation-duration: 2s; would make an animation last for 2 seconds.

ms (Milliseconds)

This unit represents a time duration in milliseconds, where 1000 milliseconds equals 1 second. It’s also used with animation and transition properties.

Example: transition-duration: 500ms; would make a transition last for 500 milliseconds, or half a second.

Time units in CSS #1:

Here’s an example of how these units might be used in a CSS rule:

div {
    transition: background-color 0.5s ease-in-out;
    animation: move 2s infinite;
}

@keyframes move {
    0% { transform: translateX(0); }
    100% { transform: translateX(100px); }
}

Code explanation:

The div element would have a transition that changes the background color over 0.5 seconds, and an animation that moves the element from its current position to 100 pixels to the right over 2 seconds. The animation repeats indefinitely due to the infinite keyword.

Time units in CSS #2:

Another example could be a delay in transition or animation:

div {
    transition: all 2s ease 1s; /* transition will start after 1 second delay */
    animation: spin 4s linear 0.5s infinite; /* animation will start after 0.5 second delay */
}

@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

Code explanation:

The div element has a transition that starts after a delay of 1 second and an animation that starts after a delay of 0.5 seconds. The animation makes the div spin indefinitely.

4. Resolution Units

Resolution units in CSS are used to specify the pixel density of output devices. They are primarily used in media queries to serve different styles to devices with different pixel densities.

dpi (Dots Per Inch)

This unit represents the number of pixels per inch.

Example: A a media query like @media (min-resolution: 300dpi) {...} would apply the styles in the curly braces only to devices with a pixel density of at least 300 dots per inch.

dpcm (Dots Per Centimeter)

This unit represents the number of pixels per centimeter. It’s similar to dpi, but uses centimeters instead of inches.

Example: @media (min-resolution: 118dpcm) {...} would apply the styles to devices with a pixel density of at least 118 dots per centimeter.

dppx (Dots Per px Unit)

This unit represents the number of dots per CSS pixel unit. A CSS pixel might correspond to multiple physical pixels on a high-density display.

Example: @media (min-resolution: 2dppx) {...} would apply the styles to devices with a pixel density of at least 2 dots per CSS pixel unit.

Resolution Units in CSS:

Here’s an example of how these units might be used in a CSS rule:

@media (min-resolution: 2dppx) {
    body {
        background-image: url("high-res-background.png");
    }
}

@media (max-resolution: 1.5dppx) {
    body {
        background-image: url("low-res-background.png");
    }
}

Code explanation:

Devices with a pixel density of 2 dots per CSS pixel unit or higher would use the high-resolution background image, while devices with a pixel density of 1.5 dots per CSS pixel unit or lower would use the low-resolution background image.

5. Angle Units

Angle units in CSS are used to specify rotation and direction. They are often used with properties like transform and gradient.

deg (Degrees)

This unit represents an angle in degrees.

Example:

transform: rotate(45deg); would rotate an element 45 degrees clockwise.

grad (Gradians)

This unit represents an angle in gradians, where 100 gradians equals a right angle.

Example:

transform: rotate(100grad); would rotate an element 90 degrees clockwise.

rad (Radians)

This unit represents an angle in radians, where 2π radians equals a full circle.

Example:

transform: rotate(3.14159rad); would rotate an element 180 degrees.

turn

This unit represents a full circle.

Example:

transform: rotate(0.5turn); would rotate an element 180 degrees.

Angle Units in CSS:

an example of how these units might be used in a CSS rule:

div {
    transform: rotate(45deg);
}

div:hover {
    transform: rotate(0.5turn);
}

Code explanation:

The div element would be rotated 45 degrees by default. When you hover over the div, it would rotate 180 degrees (0.5 of a full turn).

Bonus: Flex

fr (Fractional Unit)

This unit is used with CSS Grid Layout and represents a fraction of the available space in the grid container. If you have a grid with two columns defined as 1fr 2fr, the first column will take up one third of the available space, and the second column will take up two thirds.

Example:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
}

The total available space is divided into 3 equal parts (1fr + 2fr = 3fr), the first column takes up 1/3 of the space, and the second column takes up 2/3 of the space.

The post Understand Units in CSS: A Comprehensive Guide appeared first on Hongkiat.

10 Basic Python Tips Developers Should Know

Python is one of the most popular programming languages in the world today due to its simplicity and readability. Whether you’re a seasoned developer or a beginner, mastering Python can open up countless opportunities in fields like web development, data science, AI, and more. In this post, we’ll explore 10 Basic Python Tips Developers Should Know. These tips are designed to help you write more efficient and cleaner code, and to leverage Python’s powerful features to the fullest.

The beauty of Python lies in its simplicity and the breadth of its applications. However, to truly tap into its potential, it’s essential to go beyond the basics. This is where our handy tips come in. From list comprehensions and generators to the use of zip, map, and filter functions, these tips will help you navigate Python’s unique features and idioms.

1. List Comprehensions

List comprehensions provide a concise way to create lists based on existing lists. For example, if you want to create a list of squares from another list, you can do:

numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)  # Output: [1, 4, 9, 16, 25]
2. Generators

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off.

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for i in range(10):
    print(next(fib))  # Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
3. The with statement

The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. This is particularly useful when working with file I/O.

with open('file.txt', 'r') as file:
    print(file.read())

This code automatically closes the file after it is no longer needed.

4. Lambda Functions

These are small anonymous functions that can be created with the lambda keyword. They are useful when you need a small function for a short period of time, and you don’t want to define it using def.

multiply = lambda x, y: x * y
print(multiply(5, 4))  # Output: 20
5. The enumerate function

This is a built-in function of Python. It allows us to loop over something and have an automatic counter. It’s more pythonic and avoids the need of defining and incrementing a variable yourself.

my_list = ['apple', 'banana', 'grapes', 'pear']
for counter, value in enumerate(my_list):
    print(counter, value)

Output:

0 apple
1 banana
2 grapes
3 pear
6. Dictionary Comprehensions

Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries.

numbers = [1, 2, 3, 4, 5]
squares = {n: n**2 for n in numbers}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
7. The zip function

The zip function is used to combine two or more lists into a list of tuples.

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)  # Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
8. The map and filter functions

These functions allow you to process and filter data in a list without using a loop.

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))  # Output: [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers))  # Output: [2, 4]
9. The args and kwargs syntax

This syntax in function signatures is used to allow for variable numbers of arguments. args is used to send a non-keyworded variable length argument list to the function, while kwargs is used to send a keyworded variable length of arguments to the function.

def my_function(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key} = {value}")

my_function(1, 2, 3, name='Alice', age=25)
10. The __name__ attribute

This attribute is a special built-in variable in Python, which represents the name of the current module. It can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if __name__ == "__main__".

def main():
    print("Hello World!")

if __name__ == "__main__":
    main()

In this case, main() will only be called if this script is run directly (not imported).

The post 10 Basic Python Tips Developers Should Know appeared first on Hongkiat.