Jump to content

Blogger

Blog Bot
  • Joined

  • Last visited

    Never

Blog Entries posted by Blogger

  1. Processes are the running instances of programs that consume system resources. Listing these processes helps you monitor system activity, and  troubleshoot issues. That’s why there are multiple tools and utilities in Linux that you can use to list the currently running process. However, many beginners don’t know the exact way to list the process without errors. So, in this short article, we will explain different methods to list the process in Linux. We have divided this section into multiple parts to give you the best commands to list the processes in Linux.
    The ps Command
    The ps, or “process status,” is the most common utility to list processes in the terminal:
    ps -e
    The -e option guides ps to show every process regardless of whether the user owns those processes. Furthermore, you can customize the ps command to produce additional details using the “aux” options:
    ps aux
    The top Command
    If you desire to view the real-time list of system processes, please use the top command. It continuously updates the process list according to new and completed processes, providing more accurate results:
    top
    The above command on execution shows the list of processes as per their CPU consumption. Moreover, You can not interact with the terminal until you press “q” to quit the top utility.
    The pstree Command
    The pstree is very different from the above two commands because it displays the hierarchical relationship of processes in a tree-like structure. It helps you visually understand how a process starts and its connection with other active processes.
    pstree
    The Glances Tool
    The Glances tool provides a brief overview of the currently running process. However, you have to install the tool by running the below command: 
    Operating System Command Debian/Ubuntu sudo apt install glances Fedora sudo dnf install glances Arch Linux sudo pacman -Sy glances openSUSE sudo zypper install glances After the successful installation, you can open the Glances by running the following command:
    glances
    A Quick Summary
    Knowing how to list processes can help free up the space and turn off the currently running process. This article covered four ways– the top, ps, pstree, and pgrep commands. You can choose to use any of them according to what suits you best. We recommend you use any commands carefully, or you may get errors.
  2. by: Guest Contributor
    Tue, 31 Oct 2023 00:55:00 GMT

    In the realm of database offerings, where data is the lifeblood of modern businesses, constructing resilient systems isn't just a best practice; it's a strategic imperative. Disaster recovery planning has become a cornerstone in ensuring the continuity of operations, safeguarding valuable data, and minimizing the impact of unexpected events. This article delves into the critical factors of disaster recovery planning in database services, highlighting the essential requirements and strategies to build resilient systems that can withstand the challenges of unexpected disruptions.
    Understanding the Need for Disaster Recovery Planning
    Unpredictable Nature of Disasters
    Disasters, whether natural or human-triggered, are inherently unpredictable. From earthquakes and floods to cyber attacks and hardware failures, a myriad of events can threaten the availability, integrity, and security of database systems.
    Business Continuity and Data Integrity
    Database services play a pivotal role in the daily operations of organizations. Ensuring business continuity and maintaining data integrity are paramount, as disruptions can cause financial losses, reputational damage, and operational setbacks.
    Key Principles of Disaster Recovery Planning
    Risk Assessment and Impact Analysis
    Conduct a thorough risk assessment to identify potential threats and vulnerabilities. Additionally, perform an impact analysis to understand the effects of different disaster scenarios on database services. This foundational step guides the development of a focused and effective recovery plan.
    Define Recovery Objectives
    Clearly define recovery objectives, such as Recovery Time Objectives (RTO) and Recovery Point Objectives (RPO). RTO outlines the acceptable downtime, while RPO determines the maximum acceptable data loss in the event of a disaster. These objectives serve as benchmarks for the effectiveness of the recovery plan.
    Data Backup and Redundancy
    Implement robust data backup and redundancy strategies. Regularly back up critical data and store copies in geographically diverse locations. This ensures that, in the event of a disaster, businesses can quickly restore operations using the most recent available data.
    While both terms are often used in the same conversations, this isn’t an either/or decision. Both backups and redundancy offer two distinct and equally valuable solutions to ensuring business continuity in the face of unplanned accidents, unexpected attacks, or system failures.
    Redundancy is designed to increase your operational time, boost workforce productivity, and reduce the amount of time a system is unavailable due to a failure. Backup, however, is designed to kick in when something goes wrong, allowing you to completely rebuild regardless of what caused the failure. Moreover, if you use ELT tools for regular updating of critical data across backup and redundancy systems, maintaining seamless data access and continuity will become much easier. This becomes especially important when you stream your data to databases or data warehouses through such ELT solutions as BigQuery connectors.
    In short, redundancy prevents failure while backups prevent loss. In a modern business environment that is inherently dependent on access to large volumes of data, it’s clear that operational redundancy and backups are both critical elements of an effective continuity strategy.
    Comprehensive Documentation
    Document all aspects of the disaster recovery plan comprehensively. This includes procedures for data backup, system restoration, communication protocols, and the roles and responsibilities of the recovery team. Well-documented plans facilitate a smooth and coordinated response during crises.
    Strategies for Building Resilient Systems
    Geographical Distribution and Cloud Services
    Leverage the geographical distribution capabilities of cloud services. Distributing data across multiple regions and utilizing cloud-based databases enhances redundancy and ensures data availability even if one region is impacted by a disaster.
    Redundant Infrastructure
    Implement redundant infrastructure at both the hardware and software levels. Redundant servers, storage systems, and network components can mitigate the impact of hardware failures. Additionally, consider using load balancing and failover mechanisms to distribute workloads and ensure continuous service availability.
    Regular Testing and Simulation
    Conduct regular testing and simulation exercises to validate the effectiveness of the disaster recovery plan. Simulating different disaster scenarios, such as data corruption, network failures, or system outages, helps organizations identify weaknesses and fine-tune their recovery strategies.
    Automated Monitoring and Alerts
    Implement automated monitoring tools that continuously track the health and performance of database services. Set up alerts for critical thresholds and potential issues, enabling proactive identification of anomalies and rapid response to emerging problems.
    Incident Response and Communication
    Incident Response Team
    Form an incident response team responsible for executing the disaster recovery plan. Clearly define the roles and responsibilities of team members, ensuring that each member is well-trained and familiar with their specific duties during a disaster.
    Communication Protocols
    Establish clear communication protocols for disseminating information during a disaster. Define channels, responsibilities, and escalation procedures to ensure that stakeholders, including employees, customers, and relevant authorities, are informed promptly and accurately.
    Continuous Improvement and Adaptability
    Post-Incident Review and Analysis
    Conduct post-incident reviews and analysis after each simulation or actual disaster. This retrospective examination allows organizations to identify areas for improvement, refine recovery strategies, and enhance the overall resilience of database services.
    Adaptability to Evolving Threats
    Recognize that the threat landscape is dynamic, with new risks emerging over time. Disaster recovery plans need to be adaptable and evolve alongside technological advancements and changing security threats. Regularly update and refine the plan to address new challenges effectively.
    Scaling Disaster Recovery with Business Growth
    As businesses expand, data volume grows, and infrastructure becomes more complex. Old disaster recovery strategies and plans may now fall short. It becomes essential for businesses to evaluate and improve their disaster recovery plans to adapt to growing needs. This includes scaling resources and updating recovery objectives.
    Conclusion
    Building resilient systems through comprehensive disaster recovery planning is a crucial investment in the long-term success and viability of database services. By adhering to key principles, implementing strategic recovery strategies, and fostering a culture of continuous improvement, organizations can make their databases more robust against unexpected events. As the digital landscape evolves, the ability to recover quickly and efficiently from disasters will become a hallmark of organizations that prioritize data integrity, business continuity, and trust within their stakeholders.
  3. by: Guest Contributor
    Tue, 31 Oct 2023 00:55:00 GMT

    In the realm of database offerings, where data is the lifeblood of modern businesses, constructing resilient systems isn't just a best practice; it's a strategic imperative. Disaster recovery planning has become a cornerstone in ensuring the continuity of operations, safeguarding valuable data, and minimizing the impact of unexpected events. This article delves into the critical factors of disaster recovery planning in database services, highlighting the essential requirements and strategies to build resilient systems that can withstand the challenges of unexpected disruptions.
    Understanding the Need for Disaster Recovery Planning
    Unpredictable Nature of Disasters
    Disasters, whether natural or human-triggered, are inherently unpredictable. From earthquakes and floods to cyber attacks and hardware failures, a myriad of events can threaten the availability, integrity, and security of database systems.
    Business Continuity and Data Integrity
    Database services play a pivotal role in the daily operations of organizations. Ensuring business continuity and maintaining data integrity are paramount, as disruptions can cause financial losses, reputational damage, and operational setbacks.
    Key Principles of Disaster Recovery Planning
    Risk Assessment and Impact Analysis
    Conduct a thorough risk assessment to identify potential threats and vulnerabilities. Additionally, perform an impact analysis to understand the effects of different disaster scenarios on database services. This foundational step guides the development of a focused and effective recovery plan.
    Define Recovery Objectives
    Clearly define recovery objectives, such as Recovery Time Objectives (RTO) and Recovery Point Objectives (RPO). RTO outlines the acceptable downtime, while RPO determines the maximum acceptable data loss in the event of a disaster. These objectives serve as benchmarks for the effectiveness of the recovery plan.
    Data Backup and Redundancy
    Implement robust data backup and redundancy strategies. Regularly back up critical data and store copies in geographically diverse locations. This ensures that, in the event of a disaster, businesses can quickly restore operations using the most recent available data.
    While both terms are often used in the same conversations, this isn’t an either/or decision. Both backups and redundancy offer two distinct and equally valuable solutions to ensuring business continuity in the face of unplanned accidents, unexpected attacks, or system failures.
    Redundancy is designed to increase your operational time, boost workforce productivity, and reduce the amount of time a system is unavailable due to a failure. Backup, however, is designed to kick in when something goes wrong, allowing you to completely rebuild regardless of what caused the failure. Moreover, if you use ELT tools for regular updating of critical data across backup and redundancy systems, maintaining seamless data access and continuity will become much easier.
    In short, redundancy prevents failure while backups prevent loss. In a modern business environment that is inherently dependent on access to large volumes of data, it’s clear that operational redundancy and backups are both critical elements of an effective continuity strategy.
    Comprehensive Documentation
    Document all aspects of the disaster recovery plan comprehensively. This includes procedures for data backup, system restoration, communication protocols, and the roles and responsibilities of the recovery team. Well-documented plans facilitate a smooth and coordinated response during crises.
    Strategies for Building Resilient Systems
    Geographical Distribution and Cloud Services
    Leverage the geographical distribution capabilities of cloud services. Distributing data across multiple regions and utilizing cloud-based databases enhances redundancy and ensures data availability even if one region is impacted by a disaster.
    Redundant Infrastructure
    Implement redundant infrastructure at both the hardware and software levels. Redundant servers, storage systems, and network components can mitigate the impact of hardware failures. Additionally, consider using load balancing and failover mechanisms to distribute workloads and ensure continuous service availability.
    Regular Testing and Simulation
    Conduct regular testing and simulation exercises to validate the effectiveness of the disaster recovery plan. Simulating different disaster scenarios, such as data corruption, network failures, or system outages, helps organizations identify weaknesses and fine-tune their recovery strategies.
    Automated Monitoring and Alerts
    Implement automated monitoring tools that continuously track the health and performance of database services. Set up alerts for critical thresholds and potential issues, enabling proactive identification of anomalies and rapid response to emerging problems.
    Incident Response and Communication
    Incident Response Team
    Form an incident response team responsible for executing the disaster recovery plan. Clearly define the roles and responsibilities of team members, ensuring that each member is well-trained and familiar with their specific duties during a disaster.
    Communication Protocols
    Establish clear communication protocols for disseminating information during a disaster. Define channels, responsibilities, and escalation procedures to ensure that stakeholders, including employees, customers, and relevant authorities, are informed promptly and accurately.
    Continuous Improvement and Adaptability
    Post-Incident Review and Analysis
    Conduct post-incident reviews and analysis after each simulation or actual disaster. This retrospective examination allows organizations to identify areas for continuous improvement, refine recovery strategies, and enhance the overall resilience of database services.
    Adaptability to Evolving Threats
    Recognize that the threat landscape is dynamic, with new risks emerging over time. Disaster recovery plans need to be adaptable and evolve alongside technological advancements and changing security threats. Regularly update and refine the plan to address new challenges effectively.
    Conclusion
    Building resilient systems through comprehensive disaster recovery planning is a crucial investment in the long-term success and viability of database services. By adhering to key principles, implementing strategic recovery strategies, and fostering a culture of continuous improvement, organizations can make their databases more robust against unexpected events. As the digital landscape evolves, the ability to recover quickly and efficiently from disasters will become a hallmark of organizations that prioritize data integrity, business continuity, and trust within their stakeholders.
  4. by: Scott Robinson
    Mon, 23 Oct 2023 14:12:00 GMT

    Deleting a file in Python is fairly easy to do. Let's discuss two methods to accomplish this task using different Python modules.
    Using the 'os' Module
    The os module in Python provides a method called os.remove() that can be used to delete a file. Here's a simple example:
    import os # specify the file name file_name = "test_file.txt" # delete the file os.remove(file_name) In the above example, we first import the os module. Then, we specify the name of the file to be deleted. Finally, we call os.remove() with the file name as the parameter to delete the file.
    Note: The os.remove() function can only delete files, not directories. If you try to delete a directory using this function, you'll get a IsADirectoryError.
    Using the 'shutil' Module
    The shutil module, short for "shell utilities", also provides a method to delete files - shutil.rmtree(). But why use shutil when os can do the job? Well, shutil can delete a whole directory tree (i.e., a directory and all its subdirectories). Let's see how to delete a file with shutil.
    import shutil # specify the file name file_name = "test_file.txt" # delete the file shutil.rmtree(file_name) The code looks pretty similar to the os example, right? That's one of the great parts of Python's design - consistency across modules. However, remember that shutil.rmtree() is more powerful and can remove non-empty directories as well, which we'll look at more closely in a later section.
    Deleting a Folder in Python
    Moving on to the topic of directory deletion, we can again use the os and shutil modules to accomplish this task. Here we'll explore both methods.
    Using the 'os' Module
    The os module in Python provides a method called os.rmdir() that allows us to delete an empty directory. Here's how you can use it:
    import os # specify the directory you want to delete folder_path = "/path/to/your/directory" # delete the directory os.rmdir(folder_path) The os.rmdir() method only deletes empty directories. If the directory is not empty, you'll encounter an OSError: [Errno 39] Directory not empty error.
    Using the 'shutil' Module
    In case you want to delete a directory that's not empty, you can use the shutil.rmtree() method from the shutil module.
    import shutil # specify the directory you want to delete folder_path = "/path/to/your/directory" # delete the directory shutil.rmtree(folder_path) The shutil.rmtree() method deletes a directory and all its contents, so use it cautiously!
    Wait! Always double-check the directory path before running the deletion code. You don't want to accidentally delete important files or directories!
    Common Errors
    When dealing with file and directory operations in Python, it's common to encounter a few specific errors. Understanding these errors is important to handling them gracefully and ensuring your code continues to run smoothly.
    PermissionError: [Errno 13] Permission denied
    One common error you might encounter when trying to delete a file or folder is the PermissionError: [Errno 13] Permission denied. This error occurs when you attempt to delete a file or folder that your Python script doesn't have the necessary permissions for.
    Here's an example of what this might look like:
    import os try: os.remove("/root/test.txt") except PermissionError: print("Permission denied") In this example, we're trying to delete a file in the root directory, which generally requires administrative privileges. When run, this code will output Permission denied.
    To avoid this error, ensure your script has the necessary permissions to perform the operation. This might involve running your script as an administrator, or modifying the permissions of the file or folder you're trying to delete.
    FileNotFoundError: [Errno 2] No such file or directory
    Another common error is the FileNotFoundError: [Errno 2] No such file or directory. This error is thrown when you attempt to delete a file or folder that doesn't exist.
    Here's how this might look:
    import os try: os.remove("nonexistent_file.txt") except FileNotFoundError: print("File not found") In this example, we're trying to delete a file that doesn't exist, so Python throws a FileNotFoundError.
    To avoid this, you can check if the file or folder exists before trying to delete it, like so:
    import os if os.path.exists("test.txt"): os.remove("test.txt") else: print("File not found") OSError: [Errno 39] Directory not empty
    The OSError: [Errno 39] Directory not empty error occurs when you try to delete a directory that's not empty using os.rmdir().
    For instance:
    import os try: os.rmdir("my_directory") except OSError: print("Directory not empty") This error can be avoided by ensuring the directory is empty before trying to delete it, or by using shutil.rmtree(), which can delete a directory and all its contents:
    import shutil shutil.rmtree("my_directory") Similar Solutions and Use-Cases
    Python's file and directory deletion capabilities can be applied in a variety of use-cases beyond simply deleting individual files or folders.
    Deleting Files with Specific Extensions
    Imagine you have a directory full of files, and you need to delete only those with a specific file extension, say .txt. Python, with its versatile libraries, can help you do this with ease. The os and glob modules are your friends here.
    import os import glob # Specify the file extension extension = "*.txt" # Specify the directory directory = "/path/to/directory/" # Combine the directory with the extension files = os.path.join(directory, extension) # Loop over the files and delete them for file in glob.glob(files): os.remove(file) This script will delete all .txt files in the specified directory. The glob module is used to retrieve files/pathnames matching a specified pattern. Here, the pattern is all files ending with .txt.
    Deleting Empty Directories
    Have you ever found yourself with a bunch of empty directories that you want to get rid of? Python's os module can help you here as well.
    import os # Specify the directory directory = "/path/to/directory/" # Use listdir() to check if directory is empty if not os.listdir(directory): os.rmdir(directory) The os.listdir(directory) function returns a list containing the names of the entries in the directory given by path. If the list is empty, it means the directory is empty, and we can safely delete it using os.rmdir(directory).
    Note: os.rmdir(directory) can only delete empty directories. If the directory is not empty, you'll get an OSError: [Errno 39] Directory not empty error.
  5. 398: DevOops

    by: Chris Coyier
    Thu, 26 Jan 2023 01:30:59 +0000

    Stephen and I hop on the podcast to chat about some of our recent tooling, local development, and DevOps work. A little while back, we cleaned up our entire monorepo’s circular dependency problems using Madge and elbow grease. That kind of thing usually isn’t the biggest of deals and the kind of thing a super mature bundler like webpack deals with, but other bundlers might choke on. Later, we learned that we had more dependency issues like inter-package circular dependencies (nothing like production deployments to keep you honest) and used more tooling (shout out npx depcheck) to clean more of it up. Workspaces in a monorepo can also paper over missing dependencies — blech.
    Another change was moving off using a .dev domain for local development, which oddly actually caused some strange and hard-to-diagnose DNS issues sometimes. We’re on .test now, which should never be a public TLD.
    Time Jumps
    00:26 Dev ops spring cleaning 01:25 Local dev with .dev, wait, no, .test 06:58 Sponsor: Notion 07:54 Circular dependency 11:41 Monorepo update 13:35 Interpackage and unused packages 16:25 TypeScript 17:54 Upgrading packages 20:35 Hierarchy of packages Sponsor: Notion
    Notion is an amazing collaborative tool that not only helps organize your company’s information but helps with project management as well. We know that all too well here at CodePen, as we use Notion for countless business tasks. Learn more and get started for free at notion.com. Take your first step toward an organized, happier team, today.
  6. by: Abhishek Prakash
    Thu, 17 Apr 2025 06:27:20 GMT

    It's the release week. Fedora 42 is already out. Ubuntu 25.04 will be releasing later today along with its flavors like Kubuntu, Xubuntu, Lubuntu etc.
    In the midst of these two heavyweights, MX Linux and Manjaro also quickly released newer versions. For Manjaro, it is more of an ISO refresh, as it is a rolling release distribution.
    Overall, a happening week for Linux lovers 🕺
    💬 Let's see what else you get in this edition
    Arco Linux bids farewell. Systemd working on its own Linux distro. Looking at the origin of UNIX. And other Linux news, tips, and, of course, memes! This edition of FOSS Weekly is supported by Aiven. ❇️ Aiven for ClickHouse® - The Fastest Open Source Analytics Database, Fully Managed
    ClickHouse processes analytical queries 100-1000x faster than traditional row-oriented systems. Aiven for ClickHouse® gives you the lightning-fast performance of ClickHouse–without the infrastructure overhead.
    Just a few clicks is all it takes to get your fully managed ClickHouse clusters up and running in minutes. With seamless vertical and horizontal scaling, automated backups, easy integrations, and zero-downtime updates, you can prioritize insights–and let Aiven handle the infrastructure.
    Managed ClickHouse database | AivenAiven for ClickHouse® – fully managed, maintenance-free data warehouse ✓ All-in-one open source cloud data platform ✓ Try it for freeAiven📰 Linux and Open Source News
    The Arch-based ArcoLinux has been discontinued. Fedora 42 has been released with some rather interesting changes. Manjaro 25.0 'Zetar' is here, offering a fresh image for new installations. ParticleOS is Systemd's attempt at a Linux distribution.
    ParticleOS: Systemd’s Very Own Linux Distro in MakingA Linux distro from systemd? Sounds interesting, right?It's FOSS NewsSourav Rudra🧠 What We’re Thinking About
    Linus Torvalds was told that Git is more popular than Linux.
    Git is More Popular than Linux: TorvaldsLinus Torvalds reflects on 20 years of Git.It's FOSS NewsSourav Rudra🧮 Linux Tips, Tutorials and More
    11 vibe coding tools to 10x your dev workflow. Adding comments in bash scripts. Understand the difference between Pipewire and Pulseaudio. Make your Logseq notes more readable by formatting them. That's a new series focusing on Logseq. From UNIX to today’s tech. Learn how it shaped the digital world. Desktop Linux is mostly neglected by the industry but loved by the community. For the past 12 years, It's FOSS has been helping people use Linux on their personal computers. And we are now facing the existential threat from AI models stealing our content.
    If you like what we do and would love to support our work, please become It's FOSS Plus member. It costs $24 a year (less than the cost of a burger meal each month) and you get an ad-free reading experience with the satisfaction of helping the desktop Linux community.
    Join It's FOSS Plus 👷 Homelab and Maker's Corner
    These 28 cool Raspberry Pi Zero W projects will keep you busy.
    28 Super Cool Raspberry Pi Zero W Project IdeasWondering what to do with your Raspberry Pi Zero W? Here are a bunch of project ideas you can spend some time on and satisfy your DIY craving.It's FOSSChinmay✨ Apps Highlight
    You can download YouTube videos using Seal on Android.
    Seal: A Nifty Open Source Android App to Download YouTube Video and AudioDownload YouTube video/music (for educational purpose or with consent) with this little, handy Android app.It's FOSS NewsSourav Rudra📽️ Videos I am Creating for You
    See the new features of Ubuntu 25.04 in action in this video.
    Subscribe to It's FOSS YouTube Channel🧩 Quiz Time
    Our Guess the Desktop Environment Crossword will test your knowledge.
    Guess the Desktop Environment: CrosswordTest your desktop Linux knowledge with this simple crossword puzzle. Can you solve it all correctly?It's FOSSAbhishek PrakashAlternatively, guess all of these open source privacy tools correctly?
    Know The Best Open-Source Privacy ToolsDo you utilize open-source tools for privacy?It's FOSSAnkush Das💡 Quick Handy Tip
    You can make Thunar open a new tab instead of a new window. This is good in situations when opening a folder from other apps, like a web browser. This reduces screen clutter.
    First, click on Edit ⇾ Preferences. Here, go to the Behavior tab. Now, under "Tabs and Windows", enable the first checkbox as shown above or all three if you need the functionality of the other two.
    🤣 Meme of the Week
    We are generally a peaceful bunch, for the most part. 🫣
    🗓️ Tech Trivia
    On April 16, 1959, John McCarthy publicly introduced LISP, a programming language for AI that emphasized symbolic computation. This language remains influential in AI research today.
    🧑‍🤝‍🧑 FOSSverse Corner
    FOSSers are discussing VoIP, do you have any insights to add here?
    A discussion over Voice Over Internet Protocol (VoIP)I live in a holiday village where we have several different committees and meetings, for those not present to attend the meetings we do video conférences using voip. A few years back the prefered system was skype, we changed to whatsapp last year as we tend to use its messaging facilities and its free. We have a company who manages our accounts, they prefer using teams, paid for version as they can invoice us for its use … typical accountant. My question, does it make any difference in band w…It's FOSS Communitycallpaul.eu (Paul)❤️ With love
    Share it with your Linux-using friends and encourage them to subscribe (hint: it's here).
    Share the articles in Linux Subreddits and community forums.
    Follow us on Google News and stay updated in your News feed.
    Opt for It's FOSS Plus membership and support us 🙏
    Enjoy FOSS 😄
  7. by: Juan Diego Rodríguez
    Wed, 12 Feb 2025 14:15:28 +0000

    We’ve been able to get the length of the viewport in CSS since… checks notes… 2013! Surprisingly, that was more than a decade ago. Getting the viewport width is as easy these days as easy as writing 100vw, but what does that translate to, say, in pixels? What about the other properties, like those that take a percentage, an angle, or an integer?
    Think about changing an element’s opacity, rotating it, or setting an animation progress based on the screen size. We would first need the viewport as an integer — which isn’t currently possible in CSS, right?
    What I am about to say isn’t a groundbreaking discovery, it was first described amazingly by Jane Ori in 2023. In short, we can use a weird hack (or feature) involving the tan() and atan2() trigonometric functions to typecast a length (such as the viewport) to an integer. This opens many new layout possibilities, but my first experience was while writing an Almanac entry in which I just wanted to make an image’s opacity responsive.
    Resize the CodePen and the image will get more transparent as the screen size gets smaller, of course with some boundaries, so it doesn’t become invisible:
    CodePen Embed Fallback This is the simplest we can do, but there is a lot more. Take, for example, this demo I did trying to combine many viewport-related effects. Resize the demo and the page feels alive: objects move, the background changes and the text smoothly wraps in place.
    CodePen Embed Fallback I think it’s really cool, but I am no designer, so that’s the best my brain could come up with. Still, it may be too much for an introduction to this typecasting hack, so as a middle-ground, I’ll focus only on the title transition to showcase how all of it works:
    CodePen Embed Fallback Setting things up
    The idea behind this is to convert 100vw to radians (a way to write angles) using atan2(), and then back to its original value using tan(), with the perk of coming out as an integer. It should be achieved like this:
    :root { --int-width: tan(atan2(100vw, 1px)); } But! Browsers aren’t too keep on this method, so a lot more wrapping is needed to make it work across all browsers. The following may seem like magic (or nonsense), so I recommend reading Jane’s post to better understand it, but this way it will work in all browsers:
    @property --100vw { syntax: "<length>"; initial-value: 0px; inherits: false; } :root { --100vw: 100vw; --int-width: calc(10000 * tan(atan2(var(--100vw), 10000px))); } Don’t worry too much about it. What’s important is our precious --int-width variable, which holds the viewport size as an integer!
    CodePen Embed Fallback Wideness: One number to rule them all
    Right now we have the viewport as an integer, but that’s just the first step. That integer isn’t super useful by itself. We oughta convert it to something else next since:
    different properties have different units, and we want each property to go from a start value to an end value. Think about an image’s opacity going from 0 to 1, an object rotating from 0deg to 360deg, or an element’s offset-distance going from 0% to 100%. We want to interpolate between these values as --int-width gets bigger, but right now it’s just an integer that usually ranges between 0 to 1600, which is inflexible and can’t be easily converted to any of the end values.
    The best solution is to turn --int-width into a number that goes from 0 to 1. So, as the screen gets bigger, we can multiply it by the desired end value. Lacking a better name, I call this “0-to-1” value --wideness. If we have --wideness, all the last examples become possible:
    /* If `--wideness is 0.5 */ .element { opacity: var(--wideness); /* is 0.5 */ translate: rotate(calc(wideness(400px, 1200px) * 360deg)); /* is 180deg */ offset-distance: calc(var(--wideness) * 100%); /* is 50% */ } So --wideness is a value between 0 to 1 that represents how wide the screen is: 0 represents when the screen is narrow, and 1 represents when it’s wide. But we still have to set what those values mean in the viewport. For example, we may want 0 to be 400px and 1 to be 1200px, our viewport transitions will run between these values. Anything below and above is clamped to 0 and 1, respectively.
    In CSS, we can write that as follows:
    :root { /* Both bounds are unitless */ --lower-bound: 400; --upper-bound: 1200; --wideness: calc( (clamp(var(--lower-bound), var(--int-width), var(--upper-bound)) - var(--lower-bound)) / (var(--upper-bound) - var(--lower-bound)) ); } Besides easy conversions, the --wideness variable lets us define the lower and upper limits in which the transition should run. And what’s even better, we can set the transition zone at a middle spot so that the user can see it in its full glory. Otherwise, the screen would need to be 0px so that --wideness reaches 0 and who knows how wide to reach 1.
    CodePen Embed Fallback We got the --wideness. What’s next?
    For starters, the title’s markup is divided into spans since there is no CSS-way to select specific words in a sentence:
    <h1><span>Resize</span> and <span>enjoy!</span></h1> And since we will be doing the line wrapping ourselves, it’s important to unset some defaults:
    h1 { position: absolute; /* Keeps the text at the center */ white-space: nowrap; /* Disables line wrapping */ } The transition should work without the base styling, but it’s just too plain-looking. They are below if you want to copy them onto your stylesheet:
    CodePen Embed Fallback And just as a recap, our current hack looks like this:
    @property --100vw { syntax: "<length>"; initial-value: 0px; inherits: false; } :root { --100vw: 100vw; --int-width: calc(10000 * tan(atan2(var(--100vw), 10000px))); --lower-bound: 400; --upper-bound: 1200; --wideness: calc( (clamp(var(--lower-bound), var(--int-width), var(--upper-bound)) - var(--lower-bound)) / (var(--upper-bound) - var(--lower-bound)) ); } OK, enough with the set-up. It’s time to use our new values and make the viewport transition. We first gotta identify how the title should be rearranged for smaller screens: as you saw in the initial demo, the first span goes up and right, while the second span does the opposite and goes down and left. So, the end position for both spans translates to the following values:
    h1 { span:nth-child(1) { display: inline-block; /* So transformations work */ position: relative; bottom: 1.2lh; left: 50%; transform: translate(-50%); } span:nth-child(2) { display: inline-block; /* So transformations work */ position: relative; bottom: -1.2lh; left: -50%; transform: translate(50%); } } Before going forward, both formulas are basically the same, but with different signs. We can rewrite them at once bringing one new variable: --direction. It will be either 1 or -1 and define which direction to run the transition:
    h1 { span { display: inline-block; position: relative; bottom: calc(1.2lh * var(--direction)); left: calc(50% * var(--direction)); transform: translate(calc(-50% * var(--direction))); } span:nth-child(1) { --direction: 1; } span:nth-child(2) { --direction: -1; } } CodePen Embed Fallback The next step would be bringing --wideness into the formula so that the values change as the screen resizes. However, we can’t just multiply everything by --wideness. Why? Let’s see what happens if we do:
    span { display: inline-block; position: relative; bottom: calc(var(--wideness) * 1.2lh * var(--direction)); left: calc(var(--wideness) * 50% * var(--direction)); transform: translate(calc(var(--wideness) * -50% * var(--direction))); } As you’ll see, everything is backwards! The words wrap when the screen is too wide, and unwrap when the screen is too narrow:
    CodePen Embed Fallback Unlike our first examples, in which the transition ends as --wideness increases from 0 to 1, we want to complete the transition as --wideness decreases from 1 to 0, i.e. while the screen gets smaller the properties need to reach their end value. This isn’t a big deal, as we can rewrite our formula as a subtraction, in which the subtracting number gets bigger as --wideness increases:
    span { display: inline-block; position: relative; bottom: calc((1.2lh - var(--wideness) * 1.2lh) * var(--direction)); left: calc((50% - var(--wideness) * 50%) * var(--direction)); transform: translate(calc((-50% - var(--wideness) * -50%) * var(--direction))); } And now everything moves in the right direction while resizing the screen!
    CodePen Embed Fallback However, you will notice how words move in a straight line and some words overlap while resizing. We can’t allow this since a user with a specific screen size may get stuck at that point in the transition. Viewport transitions are cool, but not at the expense of ruining the experience for certain screen sizes.
    Instead of moving in a straight line, words should move in a curve such that they pass around the central word. Don’t worry, making a curve here is easier than it looks: just move the spans twice as fast in the x-axis as they do in the y-axis. This can be achieved by multiplying --wideness by 2, although we have to cap it at 1 so it doesn’t overshoot past the final value.
    span { display: inline-block; position: relative; bottom: calc((1.2lh - var(--wideness) * 1.2lh) * var(--direction)); left: calc((50% - min(var(--wideness) * 2, 1) * 50%) * var(--direction)); transform: translate(calc((-50% - min(var(--wideness) * 2, 1) * -50%) * var(--direction))); } Look at that beautiful curve, just avoiding the central text:
    CodePen Embed Fallback This is just the beginning!
    It’s surprising how powerful having the viewport as an integer can be, and what’s even crazier, the last example is one of the most basic transitions you could make with this typecasting hack. Once you do the initial setup, I can imagine a lot more possible transitions, and --widenesss is so useful, it’s like having a new CSS feature right now.
    I expect to see more about “Viewport Transitions” in the future because they do make websites feel more “alive” than adaptive.
    Typecasting and Viewport Transitions in CSS With tan(atan2()) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.