<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Caston Boyd on Medium]]></title>
        <description><![CDATA[Stories by Caston Boyd on Medium]]></description>
        <link>https://medium.com/@castonboyd?source=rss-2b0726ff8551------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GrS147JW4-nlxCf-oKKGgw.png</url>
            <title>Stories by Caston Boyd on Medium</title>
            <link>https://medium.com/@castonboyd?source=rss-2b0726ff8551------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:52:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@castonboyd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React JS for Beginners: Understanding the Why, Mastering the How, and Exploring the What]]></title>
            <link>https://medium.com/@castonboyd/react-js-for-beginners-understanding-the-why-mastering-the-how-and-exploring-the-what-2082aad56052?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/2082aad56052</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 14:56:15 GMT</pubDate>
            <atom:updated>2024-04-09T14:56:15.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hZK1xVsaAFVjlEyB.jpeg" /></figure><h3><strong>about the article</strong></h3><p>This article is designed to demystify the reasons behind the widespread adoption of React JS in modern web development, elucidate how it is utilized, and unravel the mechanics behind its core operations. I’ve observed that many tutorials dive straight into developing with React without addressing the foundational questions that beginners often grapple with. Transitioning from direct DOM manipulation in JavaScript to embracing a framework like React, which introduces both a steep learning curve and a novel syntax and conceptual model, can be daunting for newcomers. Therefore, this guide aims to dissect the “why,” “how,” and “what” of React JS, enriched with the development of a concise project to illustrate these concepts in action. Let’s get started by addressing the most fundamental question: Why React?</p><h3><strong>react is declarative and component based.</strong></h3><p>Before the advent of React, modern web development predominantly followed an <strong><em>imperative coding </em></strong>approach. This required developers to meticulously specify each step needed to achieve a desired outcome in the UI. To illustrate what imperative programming looks like, consider the code example provided below:</p><pre>document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br>    // Create a new paragraph element<br>    const p = document.createElement(&#39;p&#39;);<br>    p.textContent = &#39;This paragraph was added imperatively with JavaScript.&#39;;<br><br>    // Append the paragraph to the &#39;content&#39; div<br>    document.getElementById(&#39;content&#39;).appendChild(p);<br>});</pre><p>In the imperative approach example, we manually created a &lt;p&gt; tag, added text to it, and appended it to the DOM. This method might seem straightforward for a single element, but it becomes cumbersome and error-prone when dealing with multiple elements or complex UI updates. Directly manipulating the DOM in this way requires detailed, step-by-step instructions for every UI change, which can quickly lead to a tangled and hard-to-maintain codebase.</p><p>React embraces what is known as the declarative programming approach. This paradigm focuses on defining <em>what</em> the UI should look like at any given point in time, rather than detailing <em>how</em> to update it step by step. This high-level approach simplifies the process of building and maintaining complex user interfaces by abstracting the direct manipulation of the DOM.</p><pre>import React from &#39;react&#39;;<br><br>function App() {<br>  return (<br>    &lt;div id=&quot;content&quot;&gt;<br>      &lt;p&gt;This paragraph was added declaratively with React.&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this declarative approach, we simply declare the UI structure we want to achieve. The syntax used here is called JSX, which is a syntax extension for JavaScript, allowing XML-like syntax to coexist with JavaScript code. This makes it intuitive to describe UI components, blending the familiar structure of HTML with the power of JavaScript. One of the benefits of React and JSX is this seamless integration, enabling developers to construct components that encapsulate both appearance and behavior in a way that is both efficient and easy to understand.</p><p><strong><em>react is declarative.</em></strong></p><p>React simplifies building user interfaces by letting you describe what you want your UI to look like at any given moment, based on the app’s current state. You don’t need to tell the computer every step to get there. This is called “declarative” programming.</p><blockquote>For example, if your app keeps track of a score, you just tell React to display the score. React automatically updates the display whenever the score changes, without you needing to write extra code for each update.</blockquote><blockquote>In contrast, the “imperative” approach, used before React, requires you to manually manage all these changes. Using the score example, you’d need to write code that listens for changes in the score and then updates the display yourself every time the score changes.</blockquote><p>So, React’s method means you focus on what the end result should be, not on how to achieve it step by step. This makes building and updating your app’s UI more straightforward and less error-prone.</p><pre><br>/// Vanilla JS<br>const button = document.getElementById(&#39;incrementButton&#39;);<br>let counter = 0; // Counter state<br><br>button.addEventListener(&#39;click&#39;, function() {<br>  counter++; // Update the state<br>  document.getElementById(&#39;counterValue&#39;).textContent = counter; // Manually update the DOM<br>    });<br><br><br>///REACT<br>function Counter() {<br>    const [count, setCount] = useState(0); // State managed by React<br><br>    return (<br>        &lt;div&gt;<br>            &lt;div&gt;{count}&lt;/div&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p><strong><em>react is component based</em></strong></p><p>React’s component-based architecture simplifies development by allowing you to build complex user interfaces from smaller, reusable components. Here is an example of a component so I’m not just throwing words at you:</p><pre>// StaticMessage.js<br>import React from &#39;react&#39;;<br><br>function StaticMessage() {<br>  return &lt;p&gt;This is a static message!&lt;/p&gt;;<br>}<br><br>export default StaticMessage;</pre><p>What makes it reusable and easier to work with is that now I can use it as many times as i like across my program</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import StaticMessage from &#39;./StaticMessage&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;StaticMessage /&gt; /// used here <br>      &lt;StaticMessage /&gt; /// used here<br>    &lt;/div&gt;<br>  );<br>}</pre><p>What enhances its reusability and makes it easier to work with is the ability to use it multiple times throughout my program. This component-based approach makes it easier to manage your code. Instead of writing everything in one big chunk, you break it down into smaller, more manageable pieces. Plus, because these components are reusable, you can use them in multiple places throughout your application without having to rewrite the same code.</p><p><strong><em>declarative and component based. summary</em></strong></p><p>It must be stated that there are numerous reasons for choosing React for frontend development, but two reasons particularly stand out. First, React’s declarative nature allows developers to focus on the UI without worrying about the minutiae of updating the DOM (something we didnt discuss is the virtual dom). Second, its component-based architecture not only facilitates the reuse of code but also promotes a modular approach to application development.</p><p>However, adopting React also signifies a paradigm shift in how we conceive application building. Here is a quote from the React documentation:</p><blockquote>React can change how you think about the designs you look at and the apps you build. When you build a user interface with React, you will first break it apart into pieces called <strong><em>components</em></strong>. Then, you will describe the different <strong>visual states</strong> for each of your components. Finally, you will <strong>connect your components</strong> together so that the data flows through them.</blockquote><p>The quick exercise to follow will demonstrate this really quickly:</p><p>1.) building interface through components</p><p>2.) describe visual state</p><p>3.) connect components</p><h3>React Mini-Exercise: Building a Simple Interface with Components</h3><p>This exercise will guide you through creating a simple React interface, giving you a clearer understanding of the core principles of React development. While this is not a comprehensive application, as we won’t be passing data between components, it will serve as a solid foundation for you to start rendering components and seeing React in action.</p><p><strong><em>Step 1: Setup</em></strong></p><p>Go into your choice of coding editor and open your terminal. Run the following command to create a new React project with Vite:</p><pre>npm create vite@latest</pre><blockquote>Vite is not a traditional bundler. The bundle process refers to the steps involved in taking the source code of a web application (which is typically written in modular formats like ES modules or CommonJS modules) and combining or “bundling” it into a single file or a set of files that can be loaded and executed in a web browser. As an example, Webpack is a popular bundler that takes modular code and puts it together into one or more bundled files. Vite is better than other bundlers because it doesn’t bundle the entire application upfront during development. Instead, it leverages native ES modules support in modern browsers and serves code directly from the file system, providing near-instantaneous updates through its lightning-fast Hot Module Replacement (HMR) capabilities.</blockquote><p>Once you place that in the terminal you will see a few things appear on your terminal.</p><p>Project name, just type a period so that you can use the directory you created. You will see all the files appear in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*UMba0kJ3z2YwyzfGYmuVJg.png" /></figure><p>The framework, we will choose React</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*fDXwDmhuX5xPjSm2JAXH0w.png" /></figure><blockquote>You probably heard framework used a lot and have also wandered what is the difference between a library and a framework</blockquote><p>Chose Javascript + SWC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*gaInd9ZQaa92gYQBtZldGw.png" /></figure><blockquote>The term “JS with swc” refers to using the swc (Super Web Compiler) tool for compiling and transforming JavaScript/TypeScript code.</blockquote><blockquote>swc is a versatile and high-performance compiler written in Rust that aims to provide faster compilation and better language support compared to traditional tools like Babel. It supports transpiling modern JavaScript and TypeScript code to older versions of JavaScript, as well as optimizing and minifying code for production. swc is primarily designed to compile and transform modern JavaScript (ES6+) and TypeScript code into more widely supported versions of JavaScript, typically ES5 or optimized ES6+.</blockquote><p>Lastly, you should see the following instruction. Type npm install which should install all the necessary libraries for your program</p><blockquote>A library is a collection of reusable functions, classes, or data structures that developers can import and use in their own codebase. Libraries are designed to be integrated into existing projects, and developers have full control over the application’s flow and structure. Libraries are typically focused on solving specific problems or providing specific functionalities.</blockquote><p>npm run dev into your terminal. This command starts your program locally on a development server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*uy4NpD81dzVvQfpArTiwqA.png" /></figure><p>After run dev you should see the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*8WVGAsdIwNfizkceJFlC1A.png" /></figure><p>If you press command on your keyboard and hover over the url that points to your local server, you will have the option to click it. When you do, you will be directed to this a page like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7ha_WoHOFK6Nnn-ib-02w.png" /></figure><p>The above is a web page pre-generated by Vite and React.</p><p><strong><em>Step 2: looking through the folders</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*ZdXj3Lqo_vdTE0l5uyu5QA.png" /></figure><p>The files responsible for creating the pre-generated appearance of your project are outlined above. While we won’t delve into every file in detail, it’s beneficial to briefly review a few key files: vite.config.js, package.json, index.html, and main.jsx. Understanding these files will give you a foundational insight into how a Vite and React project is structured and operates.</p><ul><li>package.json: This file contains metadata relevant to the project. This includes project dependencies, scripts (like npm run dev to start the development server), and other configuration settings essential for the project setup.</li><li>index.html: The entry point for the HTML page. In a Vite and React project, this file includes a &lt;div&gt; where your React app will be rendered. It also links to the output JavaScript file that the Vite build process generates.</li><li>main.jsx: The main JavaScript file that initializes your React application. It imports React, the root App component, and renders it within the DOM element specified in index.html.</li><li>vite.config.js: The configuration file for Vite. It specifies how Vite should build and serve your project. You can customize the build process, define environment variables, and integrate plugins here to extend functionality.</li></ul><p><strong><em>Step 3: Starting from scratch</em></strong></p><ol><li>In your project directory, delete the src/styles, src/assets folders, and any unnecessary files within the src folder, leaving only main.jsx, App.jsx, and the vite.config.js file.</li><li>Open App.jsx and remove all content inside the main &lt;div&gt; tag.</li></ol><p><strong><em>Step 4: Building the interface</em></strong></p><p><em>Creating a Navbar Component:</em></p><ul><li>Inside the src folder, create a new folder named components.</li><li>Within components, create a file named Navbar.jsx.</li><li>Define a simple Navbar component with placeholder links. Example:</li></ul><pre>function Navbar() {<br>  return (<br>    &lt;nav&gt;<br>      &lt;ul&gt;<br>        &lt;li&gt;Home&lt;/li&gt;<br>        &lt;li&gt;About&lt;/li&gt;<br>        &lt;li&gt;Contact&lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/nav&gt;<br>  );<br>}<br><br>export default Navbar;</pre><p><em>Creating a Centered Name Display:</em></p><p>Still inside the components folder, create another component named CenteredName.jsx.</p><p>This component will display a name, which will later be centered on the screen. Example:</p><pre>function CenteredName() {<br>  return &lt;h1&gt;Your Name&lt;/h1&gt;;<br>}<br><br>export default CenteredName;</pre><p><em>Assembling the Components</em></p><ol><li>Open App.jsx.</li><li>Import the Navbar and CenteredName components at the top.</li><li>Include these components within the App component&#39;s return statement. Example:</li></ol><pre>import Navbar from &#39;./components/Navbar&#39;;<br>import CenteredName from &#39;./components/CenteredName&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Navbar /&gt;<br>      &lt;CenteredName /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Once you’re done, you should see something of this nature below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*qFs1icLrrAr3sIEQGpjXFQ.png" /></figure><p>We’ll add styling shortly, but even now, you can see it resembles the usual structure of HTML on the screen. We haven’t applied CSS or leveraged the full capabilities of JSX yet, which enables us to add interactivity — typically achieved with JavaScript and manipulating the DOM. This connection of HTML and JavaScript makes React a compelling framework, as it simplifies and accelerates getting started with development.</p><h4>Styling our components</h4><p><strong><em>Step 1: Creating the CSS File</em></strong></p><p>First, create a CSS file named AppStyles.css (or any name you prefer) in your project&#39;s src folder or within a dedicated styles folder inside src. Then, add the following CSS rules:</p><pre>/* AppStyles.css */<br><br>/* Style for the navbar */<br>nav {<br>  background-color: #333;<br>  color: #fff;<br>  display: flex;<br>  justify-content: space-around;<br>  padding: 1rem 0;<br>}<br><br>nav ul {<br>  list-style: none;<br>  display: flex;<br>}<br><br>nav ul li {<br>  margin: 0 10px;<br>}<br><br>/* Style for the centered name */<br>.centered-name {<br>  text-align: center;<br>  margin-top: 50px;<br>  font-size: 2rem;<br>}</pre><p><strong><em>Step 2: Integrating the CSS File with Your React Components</em></strong></p><p>In your App.jsx or the main component where you want these styles applied, import the CSS file at the top of the file.</p><pre>import &#39;./AppStyles.css&#39;; // Adjust the path based on where you placed the CSS file</pre><p><strong><em>Step 3: Adjusting Your Components to Use the Styles</em></strong></p><p>Make sure your components are set up to use the class names defined in your CSS file. Here’s an example modification for CenteredName component:</p><pre>function CenteredName() {<br>  return &lt;h1 className=&quot;centered-name&quot;&gt;Your Name&lt;/h1&gt;;<br>}</pre><blockquote>In JSX, you will notice that instead of using class to define CSS classes on HTML elements, we use className. This is because JSX is a syntax extension for JavaScript, and class is a reserved word in JavaScript. Using className within JSX tells React to render the attribute as class in the actual HTML output. This distinction ensures compatibility with JavaScript&#39;s syntax while maintaining the familiar way of assigning CSS classes to elements.</blockquote><p><strong><em>Finished example</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*zoBY3-uKfYAr42DGKtwDYQ.png" /></figure><p>This is nothing fancy but this gives you a brief sense of what React is and how quickly you can start building UI that resembles what you would do with HTML/CSS but with this awareness that you still have javascript cloaked in JSX.</p><p>A few key points to consider:</p><ul><li>Parent Container for Multiple Elements: When creating a component that includes more than two elements, those elements must be enclosed within a parent container. This can be a traditional HTML element like a &lt;div&gt;, or you can use React&#39;s fragment shorthand, &lt;&gt;...&lt;/&gt;, for cases where you don&#39;t need an enclosing element in the DOM for styling or scripting purposes.</li></ul><p><strong><em>Without a parent container</em></strong> <em>(this will cause an error because JSX expressions must have one parent element)</em>:</p><pre>function MyComponent() {<br>  return (<br>    &lt;h1&gt;Welcome to MyComponent&lt;/h1&gt;<br>    &lt;p&gt;This is a paragraph within MyComponent.&lt;/p&gt;<br>  );<br>}</pre><p><strong><em>With a </em></strong><strong><em>&lt;div&gt; as a parent container:</em></strong></p><pre>function MyComponent() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to MyComponent&lt;/h1&gt;<br>      &lt;p&gt;This is a paragraph within MyComponent.&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong><em>Using React Fragments (</em></strong><strong><em>&lt;&gt;...&lt;/&gt;) as a parent container:</em></strong></p><pre>function MyComponent() {<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Welcome to MyComponent&lt;/h1&gt;<br>      &lt;p&gt;This is a paragraph within MyComponent.&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><ul><li>The Role of index.html and main.jsx: The interaction between index.html and main.jsx marks the starting point of your application. The process unfolds as follows: your app is served to the browser, which then reads the root element specified in index.html. React uses ReactDOM.createRoot to associate this root with your React app. By calling getElementById, React finds this root element and sets it as the root of your React element tree, with &lt;App /&gt; serving as the entry point for rendering.</li><li>Understanding Component Hierarchy: The App component marks the beginning of your component hierarchy, serving as the root from which all other components branch out. To better understand and visualize the component hierarchy within your application, consider using developer tools designed for React, such as the React Developer Tools extension for Chrome or Firefox. After installing, you can inspect your component hierarchy directly within your browser’s development tools, providing valuable insights into how your components are structured and interact.</li></ul><p>Stay tune for more on React.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2082aad56052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronous and Asynchronous Programming]]></title>
            <link>https://medium.com/@castonboyd/synchronous-and-asynchronous-programming-d982a7bfff31?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/d982a7bfff31</guid>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 11:05:47 GMT</pubDate>
            <atom:updated>2024-04-08T11:05:47.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*irBXiBCrRMJS18MfdGg0Kw.jpeg" /><figcaption>from Scaler Topics</figcaption></figure><p><strong><em>What is synchronous coding?</em></strong></p><p>If you’re familiar with coding, you know that code usually runs in a specific sequence, known as sequential execution. This means that when a compiler — or your computer — processes a program, it executes the code line by line, following the order in which it’s written. This ordered process is referred to as the program’s execution flow or control flow. For an example, consider a scenario where I have two functions nested within a larger function:</p><pre>// first function<br>function sync_one() {<br>    console.log(&quot;sync_one is running.&quot;);<br>}<br><br>// second function<br>function sync_two() {<br>    console.log(&quot;sync_two is running.&quot;);<br>}<br><br>// final function that calls the previous two functions<br>function finalSync() {<br>    sync_one(); // Call the first function<br>    sync_two(); // Then call the second function<br>    console.log(&quot;finalSync has finished running both functions.&quot;);<br>}<br><br>// programs execute functions that are called, so it starts here<br>finalSync();</pre><p>In the example provided, the execution begins with the finalSync() function. Within finalSync, the sync_one() function is called first, followed by sync_two(). This exemplifies synchronous code, where the program&#39;s execution flow waits for each function to complete before proceeding to the next. In essence, the code runs in a natural, orderly sequence, ensuring that sync_one() completes its execution before sync_two() starts, and so forth.</p><p>Programs traditionally exhibit a synchronous nature, especially in environments where all operations are local and the execution environment is predominantly single-threaded. In such a context, when a function calls another function, the calling function waits for the called function to complete its execution before proceeding. This behavior underlines the sequential execution model, where tasks are performed one after the other in a clearly defined order.</p><blockquote><strong>Side Note on Single-Threaded Execution:</strong> In environments like JavaScript’s runtime in web browsers, where execution is single-threaded, only one operation can be carried out at a time. This implies that if one operation is in progress, others must wait their turn until the current operation is complete. This sequential approach streamlines both program execution and the debugging process. However, it necessitates thoughtful arrangement of tasks to ensure the system remains performant and responsive. This is especially true for tasks that are I/O-bound or require waiting for external resources, such as making network requests to servers for data retrieval (from databases or APIs). To observe single-threaded execution in action, you might experiment by running the provided code example above in<strong> </strong><a href="https://pythontutor.com/"><strong>pythontutor.com</strong> </a>to visualize the call stack and the execution order.</blockquote><p><strong><em>Issue with Synchronous Coding:</em></strong></p><p>Now, I’ll present a straightforward example to illustrate the issue with synchronous coding. If you’re seeking a more in-depth explanation, please visit <a href="https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/">this link</a> for additional information.</p><p>Imagine you’re building a web application that displays user profiles fetched from a database or an external API.</p><blockquote><strong>Side Note:</strong> Fetching data from a database or an external API is similar to asking someone to bring you a book from another room or even a distant library. It takes time for the request to be made, for the person (or system) to find the book, and to bring it back to you. In the context of web development, this “asking and retrieving” (request/response )process happens over the internet, where the application requests data, waits for the data source to respond, and then receives the data.</blockquote><p>If you use synchronous coding to retrieve this data, the application will “freeze” or become unresponsive until the data is fully loaded. This is because the JavaScript runtime environment must wait for each data retrieval operation to complete before it can move on to execute subsequent code, including UI updates. Try the example below:</p><pre>// Hypothetical function to simulate a synchronous data retrieval<br>// WARNING: JavaScript does not support synchronous network requests using fetch like this;<br>// this is just a conceptual illustration.<br>function getUserSync(userId) {<br>    const start = Date.now();<br>    console.log(`Starting data retrieval for user ${userId}...`);<br><br>    // Simulate a delay for data retrieval, e.g., waiting for a network response<br>    while (Date.now() &lt; start + 5000); // Wait for 5 seconds<br><br>    console.log(`Data retrieved for user ${userId}`);<br>    return { id: userId, name: &quot;John Doe&quot; }; // Simulated user data<br>}<br><br>console.log(&quot;Before data retrieval&quot;);<br>const user = getUserSync(1); // This will &quot;block&quot; for 5 seconds<br>console.log(`User retrieved: ${user.name}`);<br>console.log(&quot;After data retrieval&quot;);</pre><p><strong><em>Why asynchronous programming?</em></strong></p><p>When working with programs that need to perform multiple tasks simultaneously, it’s important that the application remains responsive. For instance, you wouldn’t want your Instagram app to freeze entirely while it’s loading data, preventing you from interacting with other parts of the user interface (UI). Asynchronous programming allows certain tasks to run in the background, so the app doesn’t have to wait for these tasks to finish before moving on. This means you can continue interacting with the app, even as you wait for you name or other information to be displayed that is being fetched from the back.</p><p>The example below demonstrates setTimeout, an asynchronous function in JavaScript. For more details, you can refer to <a href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout"><strong>MDN documentation</strong></a>.</p><pre><br>console.log(&#39;First&#39;);<br><br>// Set a timeout for 2 seconds - setTimeout is async code<br>setTimeout(() =&gt; { console.log(&#39;Second&#39;); }, 2000);<br><br>console.log(&#39;Third&#39;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*FKRgQNBr1OuqyPc3CimGWg.png" /></figure><p>When running this code, you might expect the output to follow the order First, Second, then Third. However, the actual output is First,Third, and then Second. Why is this? The explanation lies in the asynchronous nature of setTimeout. The code execution starts synchronously, printing First. When it encounters setTimeout, instead of pausing execution for 2 seconds, JavaScript schedules Secondto be printed later and moves on, printing Third in the meantime. This behavior demonstrates asynchronous execution, where setTimeout allows the code to continue running without waiting for the delay to finish. Second appears after Third, showcasing how asynchronous functions like setTimeout enable <strong><em>non-blocking</em></strong> code execution.</p><blockquote><strong>Sidenote: </strong>JavaScript is single-threaded, meaning it can process only one command at a time. To handle asynchronous operations, such as network requests or timers, it leverages the libuv library. This library allows JavaScript to perform non-blocking I/O operations by offloading tasks to the background, then running a callback once the task is completed. This approach is central to how Node.js operates efficiently despite JavaScript’s single-threaded nature. While the intricacies of how libuv works are beyond the scope of this explanation, understanding it can greatly enhance your grasp of asynchronous programming in JavaScript. For a deeper dive into how JavaScript manages to be highly performant and handle asynchronous operations despite being single-threaded, consider exploring resources on the Event Loop and libuv. <a href="https://dev.to/nodedoctors/an-animated-guide-to-nodejs-event-loop-3g62">Here’s a resource</a> to get started on learning about the Event Loop and libuv in the context of Node.js.</blockquote><p><strong><em>Fetch API</em></strong></p><p>The fetch API is an asynchronous feature in JavaScript used to make network requests to servers, which can be located anywhere across the internet. This capability is for accessing or submitting data to remote databases, APIs, or other resources online. By being asynchronous, fetch lets your program initiate a data request and then continue executing other tasks while waiting for the response. This means you&#39;re not stuck waiting for the network operation to complete before the rest of your code can run.</p><pre>console.log(&#39;Before fetch call&#39;);<br><br>fetch(&#39;https://jsonplaceholder.typicode.com/posts/1&#39;)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; console.log(&#39;Data fetched:&#39;, data))<br>  .catch(error =&gt; console.log(&#39;Fetch error:&#39;, error));<br><br>console.log(&#39;After fetch call&#39;);</pre><p>In this example, the console will log “Before fetch call” and “After fetch call” in quick succession, demonstrating that the program doesn’t pause at the fetch call. The fetched data (or an error, if the request fails) is logged only after the asynchronous request completes, showcasing how other parts of your code can run without being held up by the network request.</p><p><strong><em>In Summary</em></strong></p><p>This article offered a concise overview of synchronous and asynchronous programming concepts. While we’ve touched on the basics, there are more intricate details and related concepts, such as multithreading, that further expand on these foundational ideas. The essence of this discussion is to highlight how synchronous code executes in the order it’s written, mirroring our intuitive approach to coding. In contrast, asynchronous programming allows us to manage tasks that, if executed synchronously, would significantly hinder performance, especially in single-threaded environments. Asynchronous operations allow our programs to remain responsive and efficient, enabling tasks to run simultaneously without waiting for each one to complete sequentially.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d982a7bfff31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Request-Response Cycle Through A Story]]></title>
            <link>https://medium.com/@castonboyd/request-response-cycle-through-a-story-e552a7afff41?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/e552a7afff41</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 12:59:45 GMT</pubDate>
            <atom:updated>2024-04-02T12:59:45.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*89VkqUpOJvd5CfB3.png" /></figure><p><strong>What is the request-response cycle?</strong></p><p>The request-response cycle is a fundamental concept in software development that describes the <strong><em>communication process between a client application and a server.</em></strong> This cycle is initiated when the client application makes a request to the server to access specific resources. These resources can vary widely, including web pages, data files, or any information the server is set up to provide. To illustrate this concept, I wrote a narrative about Mike, a developer making a web application. Through Mike’s journey, we’ll explore the utilization of the request-response cycle both in a local development setting — referred to simply as “development” — and later, as he transitions his project onto the wider internet for public accessibility, a stage known as “production.”</p><p><strong>Request-Response Cycle Locally (Development)</strong></p><p>Mike embarked on a journey to create a website that could be accessible to everyone on the internet. His first step involved writing the website’s program using HTML, CSS, and JavaScript. Each piece of the website was developed in separate files, which Mike wrote and tested on his computer, locally. <strong><em>Running a website locally </em></strong>means that the website files are stored on one’s own computer, and the site can only be accessed by that same computer, not from the wider internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0SNIUZLaXkcb4qv6c9sxw.png" /></figure><blockquote>When you work locally, what’s happening is your computer’s private IP address is being used to interact with the software or services running on your own machine. This private IP address is unique within your local network but not across the internet. It allows your computer to communicate with other devices on your home or office network, such as printers, other computers, or internet-connected devices, but it is not directly accessible from the internet. This setup is useful for testing, development, or running applications that don’t need to be accessed outside of your local network. It provides a layer of security, as devices on the internet cannot directly access your computer unless specific configurations, like port forwarding, are set up on your router.</blockquote><p>In the depicted scenario, Mike is developing a web application using HTML, CSS, and JavaScript, all of which he authors within a popular code editor called Visual Studio Code (VS Code). To streamline his development process, Mike employs an extension for VS Code known as Live Server. This tool automatically serves his files directly to his default web browser, Google Chrome, allowing for immediate viewing and interaction with his project.</p><blockquote>Live Server operates by translating the URL of Mike’s project — a URL that, in essence, represents an IP address — from its numeric form into a more human-readable format (such as <a href="http://www.example.com/">www.example.com</a>). However, during development, instead of using a global IP address, Live Server utilizes a loopback address, an address that devices use to refer to themselves sometimes called <strong>localhost</strong>. This special address directs requests back to Mike’s own device, allowing his browser to communicate directly with the local server established by Live Server. <strong>Note:</strong> most devices have a <strong>local</strong>, <strong>global,</strong> and <strong>loopback address</strong></blockquote><p>As Mike makes changes to his code, or as he navigates between different pages of his site (for instance, from the homepage to an “About” page), Live Server dynamically updates the content shown in Chrome. This is made possible by the loopback address, which ensures that all requests and responses during the development phase are contained within Mike’s local environment, enabling a seamless and efficient workflow.</p><p><strong>Request-Response Cycle Publicly (Production)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwgxZogZeleUD6USCXobNA.png" /></figure><p>When Mike decided to take his locally developed website or web application and make it available on the internet, he opted for GitHub as a straightforward hosting solution, given its simplicity and direct integration with his development workflow. By pushing his project to a GitHub repository, Mike effectively leveraged GitHub’s servers, which are configured to serve web content globally.</p><p>Upon activating GitHub Pages for his repository, Mike’s project was instantly hosted on GitHub’s infrastructure. This meant his website was now accessible through a unique URL provided by GitHub, essentially assigning his project a global reach. This URL is similar to a global IP address in that it allows anyone, anywhere, to access Mike’s site by entering this address into their web browser, such as Chrome or Firefox.</p><p>The magic behind serving Mike’s site to anyone in the world starts when a request is made to this URL. GitHub’s servers, acting as the backbone for GitHub Pages, receive the request for Mike’s website. These servers then look up the necessary files in Mike’s repository — whether they’re HTML, CSS, or JavaScript files — and send them back to the requesting browser. This response allows the browser to render Mike’s site for the viewer.</p><p><strong>Conclude:</strong></p><p>Mike’s journey from local development to global production showcases how his browser, specifically Google Chrome, <strong><em>requests </em></strong>and displays the files he coded to create his website. This process involves:</p><ol><li>Google Chrome sending requests for the necessary files, which are stored either locally during development or on a hosting service’s server in production.</li><li><strong><em>The server then responds </em></strong>(live server or Github), providing the files for Chrome to render Mike’s website for viewing.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e552a7afff41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Created a To-do List]]></title>
            <link>https://medium.com/@castonboyd/created-a-to-do-list-5db236ba708b?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/5db236ba708b</guid>
            <category><![CDATA[html-css-javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[to-do-list]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 15:41:30 GMT</pubDate>
            <atom:updated>2024-03-18T16:57:25.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a To-do List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzOF8nINey6qiwoFnd8seA.gif" /></figure><p><strong>Table of Contents </strong><br>1. Setup — Connect files: SASS, CSS, HTML, and JS<br>2. HTML — Analyze mockup and structure HTML<br>3. CSS/SASS — Before and after, apply style to HTML<br>4. JS — Add functionality to HTML<br>5. Summary</p><h3>SETUP</h3><p>In this section we will connect our initial files together to ensure we have a smooth development setup. Start with main html file, then connect our SASS, and then connect our JS file.</p><p><strong><em>HTML</em></strong></p><ol><li>Create index.html File</li><li>Add index.html to Workspace</li><li>Add Boilerplate Markup (inital html text)</li><li>Run Server</li></ol><p><strong><em>SASS</em></strong></p><ol><li><em>Create a styles folder to add your SASS/CSS files.</em></li><li><em>Create Your Sass File:<br> 1. </em>Open your code editor or IDE (like Visual Studio Code).<br> 2. Create a new file with the extension .scss for SCSS syntax (e.g., styles.scss).<br>3. Make sure the file is in your styles folder.</li></ol><p>3.<em> Write Your Sass Code:<br> </em>Begin writing your Sass code in the file. Here’s an example of how you might use variables and nesting in SCSS:</p><pre>body {<br>  background-color: green; /// This is just for testing <br>}</pre><p>4.<em> Compile Your Sass to CSS:<br> </em>Use the Sass command-line tool to compile your .scss or .sass file to .css. Open your terminal or command prompt, navigate to the directory containing your Sass file, and run the following command:</p><pre>sass --watch styles/styles.scss:styles/styles.css</pre><blockquote>Browsers can only interpret CSS, not Sass files. This necessitates converting Sass (.scss or .sass) files into CSS, which browsers can understand and apply to web pages. You might wonder why bother with Sass at all. The answer lies in the enhanced coding experience Sass provides. Sass introduces features like variables, mixins, nested rules, and functions, allowing for more organized, maintainable, and concise code. In essence, you write your styles in a more efficient and readable way using Sass, and then compile them into the standard CSS that browsers require.</blockquote><p>5. <em>Link the Compiled CSS to Your HTML:</em></p><ul><li>Ensure your HTML file links to the compiled CSS file, not the Sass file, since browsers do not understand Sass directly.</li></ul><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;</pre><p>6. Verify the successful linkage of your Sass file by observing changes on your server-rendered webpage.</p><p><strong><em>JS</em></strong></p><ol><li>Create a file named script.js in your project directory.</li><li>Inside script.js, add a line of JavaScript: console.log(&#39;Script is loaded successfully.&#39;);</li><li>Add the script to your HTML file: &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;, placing this line before the closing &lt;/body&gt; tag.</li><li>Open your webpage in a browser, right-click, select “Inspect”, navigate to the “Console” tab, and check for the message “Script is loaded successfully.”</li></ol><h3><strong>HTML — Analyze the mockup and structure the HTML accordingly</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAR5AwEOPlewlCF9MIjTcw.png" /></figure><p>Before constructing a webpage, it’s crucial to analyze the mockup to understand the structure and relationships between elements — whether they’re parents, children, or siblings. Identifying each element’s role and relationship helps in organizing the content logically and semantically. Also, adopting a consistent naming convention, like BEM, provides clarity for you and structure to your CSS, making it easier to maintain and understand. If you’re unfamiliar with BEM and would like to learn more, <a href="https://andrew-barnes.medium.com/bem-and-sass-a-perfect-match-5e48d9bc3894"><strong>click here</strong></a><strong>.</strong></p><p><strong><em>Thinking through the structure</em></strong></p><p>What you see above is an outline from Excalidraw that I created while considering the element structure needed for a to-do list. The process isn’t overly complex, but it’s a beneficial exercise to engage in. This is the thought process:</p><ol><li>The body will serve as my primary container, so it&#39;s outlined in <strong>black</strong>, representing the highest level in the hierarchy of the webpage.</li><li>The header element, designated as todo--header, acts as a specific container for the title and potentially other navigational elements. It&#39;s a direct child of the body and is the entry point for the content structure.</li><li>Within the header, the h1 element with the class todo--header__title serves as a child element that holds the main title of the to-do list, reinforcing the hierarchy as it sits within the header container.</li><li>The section element, styled as todo--section, is another primary container that will hold the core functional parts of the to-do list, such as the form and the list itself.</li><li>The form element, labeled todo--form, is a nested container within the section. It will contain all form-related elements, establishing a parent-child relationship with the inputs and buttons it encloses.</li><li>The input field, given the class todo--form__input, is a child element within the form container, designated for user input to add new to-do items.</li><li>The to-do list itself, possibly marked up as a ul with the class todo--form__todo-list, represents a collection of items, each an li element. This list is a child of the form and a sibling to the input field.</li></ol><p>Once I have a clear understanding of the structure and relationships between elements, I proceed to assemble the HTML. The resulting code is as follows:</p><pre>&lt;body&gt;<br>    &lt;header class=&quot;todo-header&quot;&gt;<br>        &lt;h1 class=&quot;todo-header__title&quot;&gt;todos&lt;/h1&gt;<br>    &lt;/header&gt;<br>    &lt;section class=&quot;todo-section&quot;&gt; <br>        &lt;form class=&quot;todo-form&quot; id=&quot;todo-form&quot;&gt; <br>            &lt;input type=&quot;text&quot; class=&quot;todo-form__input&quot; placeholder=&quot;Enter your to do&quot; autocomplete=&quot;off&quot;&gt;<br>            &lt;ul class=&quot;todo-form__todo-list&quot;&gt;&lt;/ul&gt;<br>        &lt;/form&gt;<br>    &lt;/section&gt;<br>&lt;/body&gt;</pre><h3><strong>CSS/SASS — Before and after, apply style to HTML</strong></h3><p>Before I dive into styling, I carefully evaluate the current state of my HTML and determine what is required to bridge the gap between it and the mockup. I consider which CSS properties and values will bring my code closer to the intended design. Below is an image and an accompanying analysis detailing what components are currently missing and what additions are necessary to achieve the desired outcome:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCCR7zHN6B7-_Rpamtt1aQ.png" /></figure><p>With service level observations, we can surmise the following:</p><ol><li><strong>Central Placement of Input Box and Title: </strong>On the right side, the input box is centrally placed within the layout. Flex or grid layout</li><li><strong>Color and Typography:</strong> The mockup on the right has a softer background color, and the text “todos” is a lighter shade.</li><li><strong>Styling of the Input Box: </strong>The input box on the right has a more pronounced and rounded styling, suggesting the need for CSS border-radius, border-color, and padding properties.</li><li><strong>Spacing and Layout: </strong>There seems to be more space around the “todos” title and around the input box in the mockup, which means margin and padding CSS properties will need to be applied to achieve the same spacious layout.</li><li><strong>Drop Shadow and Depth:</strong> The mockup has a subtle shadow around the container, giving it depth. This effect can be achieved with the CSS box-shadow property.</li><li><strong>Font Weight and Size:</strong> The title “todos” on the right looks to be of a larger font size and possibly a lighter font weight than on the left, requiring changes to the font-size and font-weight CSS properties.</li></ol><p><strong>Our next step will be to actually achieve this look.</strong></p><p><strong><em>Central Placement of Input Box and Title</em></strong></p><p>To begin with a clean slate, I reset the default margin and padding across all elements. This ensures consistency and gives me full control over the layout. I also just start with a base font of 20px so I can apply em across all other fonts needed in the children elements. The universal selector (*) is used to apply these base styles to every element:</p><pre>* {<br>  margin: 0;<br>  padding: 0;<br>  box-sizing: border-box;<br>  font-size: 20px;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*2k6KWpb8qrWrCYsoM2zGPw.png" /></figure><p>Understanding that the body tag will act as the parent container for my page elements, I&#39;ve employed a grid display to manage the layout of its direct children—namely, the header and section elements. By setting up the grid on the body, I ensure that everything within it, including the nested children within the header and section, can be centered and neatly organized according to my design requirements.</p><pre>  html, body {<br>    width: 100%;<br>    height: 100%;<br>    display: grid;<br>    grid-template-rows: repeat(2, auto);<br>    align-content:center;<br>    justify-items: center;<br>    background-color: #f0f4f0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*bn1Wt_f6rMwPWW_1ebRcCQ.png" /></figure><p><strong><em>Color and Typography</em></strong></p><p>We changed the background color for the body and added the color #f0f4f0 to give a soft green background. Now we’ll turn our attention to the header.</p><p><em>font size and color:</em></p><ul><li>font-size: 3rem; - This property is scaling the font size up to three times the root element&#39;s font size. We set that the root (html) font size to 20px, 3rem translates to 60px. This larger font size makes the title more prominent and matches the mockup&#39;s design.</li><li>Font family: Poppins (import this from google )</li><li>color: #a6e9a8; - The color property changes the font color to a soft green, which provides a gentle, welcoming look as seen in the mockup.</li></ul><pre>.todo-header {<br>    &amp;__title { <br>        font-size: 3rem; <br>        color: #a6e9a8;<br>        font-family: &#39;Poppins&#39;, &#39;Helvetica Neue&#39;;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*nCKSdcYlnb5qbf5x7wY3tg.png" /></figure><p><em>position of title:</em></p><p>There are several methods to position a title, but for demonstration purposes, I chose to showcase the grid layout’s capabilities in controlling your layout. Recall that we’ve set the bodyto display as a grid, meaning every element within the bodyis placed within this grid structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UG_zDdWcGUdUk5Jv734ExQ.png" /></figure><p>Every cell within the grid functions as an individual container with its own width and height, just like any other element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVGVwq-ASzutypIAFT2UJQ.png" /></figure><p>In a grid layout, .todo-header__title and the input box are each contained within their own grid cells. To introduce space between these cells, we have a couple of options:</p><ol><li>Margin: By applying margin-bottom to the .todo-header__title grid cell, we can create space between the title cell and the input box cell below it. This approach directly affects the spacing of the specific element with the margin.</li><li>Row Gap: Alternatively, we can use the row-gap property on the grid container to establish uniform space between all rows within the grid. This method ensures consistent spacing between every element separated by a row, applying the specified gap in pixels to the entire grid.</li></ol><p>Both methods are effective, but row-gap provides a more consistent and grid-focused way to manage spacing between all row elements collectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d4bzvvBz2HsWTt1FIgQKaA.png" /></figure><p>When applying row-gap, it&#39;s important to note that this property should be set on the grid container, which is the parent element that defines the grid layout. In our scenario, the body element is the grid container. It&#39;s responsible for displaying and arranging all the grid cells within it. Adding row-gap to the body will uniformly distribute space between all rows in the grid, affecting all the child elements accordingly.</p><pre>  html, body {<br>    width: 100%;<br>    height: 100%;<br>    font-family: &#39;Poppins&#39;, &#39;Helvetica Neue&#39;;<br>    font-size: 20px;<br>    display: grid;<br>    grid-template-rows: repeat(2, auto);<br>    row-gap: 30px; ///ADDED THIS HERE, any space between 20px - 30px will work<br>    align-content:center;<br>    justify-items: center;<br>    background-color: #f0f4f0;<br>}</pre><p><strong><em>Styling of the Input Box</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3lpZThhJW7H2G-sUh99yQ.png" /></figure><p>If we examine the image above, we observe the following differences between the input box on the left and the one on the right:</p><ol><li><strong>Styling: </strong>The input box on the right has a styled border, rounded corners, and a subtle shadow, giving it a more polished and tactile appearance.</li><li><strong>Color: </strong>The input text and placeholder text colors on the right appear lighter, providing a softer contrast against the input box’s background.</li><li><strong>Padding:</strong> The input box on the right has more padding inside it, creating more space around the text. This makes the content less cramped and more visually appealing.</li><li><strong>Background:</strong> There is a background color applied to the input box on the right, which differentiates it from the rest of the form and the page.</li></ol><pre>.todo-form {<br>    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);<br>    &amp;__input { <br>            border: none;<br>            color: black;<br>            font-size: 1rem;<br>            padding: 0.5rem 0.5rem;<br>            display: block;<br>            background-color: #ecfaed;<br>          }<br>        &amp;__input::placeholder {<br>            color: #a6e9a8;<br>        }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*4PoLXW_m_0-JIO4aF8HKsQ.png" /></figure><h3>JS — Add functionality to HTML</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzOF8nINey6qiwoFnd8seA.gif" /></figure><p>Our to-do list features interactive functionality where entering a task creates a new list item displayed beneath the input field. To make our to-do list interactive, we’ll utilize DOM manipulation with JavaScript. This allows us to dynamically add, remove, or modify HTML elements in response to user actions. If you need to brush up on DOM manipulation or seek a deeper understanding, you might find this <a href="https://medium.com/@castonboyd/the-dom-made-simple-1be648631ac4">article on DOM manipulation</a> helpful.</p><p><strong><em>Actions first and then elements</em></strong></p><p>Before manipulating the DOM with JavaScript, it’s important to identify the user interactions, commonly referred to as ‘events’, that trigger changes on the page. From the GIF image, we observe the following events:</p><ol><li><strong><em>A user types in the input box and submits their entry. </em></strong>This can be considered as an ‘input’ or ‘submit’ event, depending on whether the interaction is captured upon each keystroke or when the user finalizes their entry, typically through a form submission.</li><li>When the user submits their to-do item, an ‘add’ event occurs, resulting in a <strong><em>new list item being created</em></strong> and displayed below the input box.</li><li><strong><em>By clicking on the text of the list item, a ‘toggle’ event is fired,</em></strong> which toggles a strikethrough style on the text to indicate completion or incompletion.</li><li><strong><em>Clicking on the ‘X’ associated with a list item triggers a ‘remove’ or ‘delete’ event,</em></strong> which removes the item from the list.</li></ol><p><strong><em>A user types in the input box and submits their entry.</em></strong></p><p>To enable functionality in the input field, we begin by acquiring references to the relevant HTML elements in the JavaScript code. This acquisition process is carried out by using document.getElementById to select elements by their respective IDs. Once these elements are targeted, we can then assign event listeners to them, which will handle user-triggered events. For our purposes, we&#39;re interested in detecting when the form is submitted and capturing the input data, which necessitates the use of specific IDs for these elements.</p><pre>    &lt;section class=&quot;todo-section&quot;&gt; <br>        &lt;form class=&quot;todo-form&quot; id=&quot;todo-form&quot;&gt; <br>            &lt;input type=&quot;text&quot; id=&quot;todo-input&quot; class=&quot;todo-form__input&quot; value=&quot;&quot; placeholder=&quot;Enter your todo&quot; autocomplete=&quot;off&quot;&gt;<br>            &lt;ul class=&quot;todo-form__todo-list&quot;&gt;&lt;/ul&gt;<br>        &lt;/form&gt;<br>    &lt;/section&gt;</pre><p>To set up our to-do list functionality, we need to interact with both the form and the input field. Specifically, we must detect when a user submits the form, typically by pressing the ‘Enter’ key, and capture the data entered in the input field.</p><pre>const todoForm = document.getElementById(&#39;todo-form&#39;);<br>const todoInput = document.getElementById(&#39;todo-input&#39;);<br><br>todoForm.addEventListener(&#39;submit&#39;, () =&gt; {<br>  console.log(todoInput.value)<br>});</pre><p>If you’ve observed, every time you submit the form, the console flashes the input value briefly before it vanishes. This happens because we need to prevent the form’s default submission behavior, which typically refreshes the page. To stop this from happening, we add an event parameter, commonly named e, to our event handler function and call the e.preventDefault() method within it.</p><pre>const todoForm = document.getElementById(&#39;todo-form&#39;);<br>const todoInput = document.getElementById(&#39;todo-input&#39;);<br><br>todoForm.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>  e.preventDefault(); /// prevent default behavior <br>  console.log(todoInput.value)<br>});</pre><p><strong><em>new list item being created</em></strong> a</p><p>To ensure the entered value appears as a styled list item below the input field, you need to create the list item element, set its text content, and apply the appropriate styles. Begin by accessing the unordered list in your HTML, like this:</p><pre>&lt;ul class=&quot;todo-form__todo-list&quot; id=&quot;todo-list&quot;&gt;&lt;/ul&gt;<br>    &lt;section class=&quot;todo-section&quot;&gt; <br>        &lt;form class=&quot;todo-form&quot; id=&quot;todo-form&quot;&gt; <br>            &lt;input type=&quot;text&quot; id=&quot;todo-input&quot; class=&quot;todo-form__input&quot; value=&quot;&quot; placeholder=&quot;Enter your todo&quot; autocomplete=&quot;off&quot;&gt;<br>            &lt;ul class=&quot;todo-form__todo-list&quot; id=&quot;todo-list&quot;&gt;&lt;/ul&gt; /// TARGET<br>        &lt;/form&gt;<br>    &lt;/section&gt;</pre><pre><br>const todoList = document.getElementById(&#39;todo-list&#39;); // Access the unordered list</pre><p>With todoList now targeting the appropriate element, you can proceed to add new items to it:</p><pre>const todoEl = document.createElement(&#39;li&#39;); // Create a new &#39;li&#39; element<br>todoEl.textContent = todoInput.value; // Set the text content of the &#39;li&#39; to the input value<br>todoList.appendChild(todoEl); // Append the new &#39;li&#39; to the &#39;ul&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkdZ--JciXIwOIGWzXRN3g.png" /></figure><p>In transitioning from the basic layout on the left to the more polished design on the right, we’ll tackle a few key styling changes.</p><ul><li>First, we’ll address the input box. By default, browsers may highlight input fields with an outline when they’re focused. To remove this, we will reset the outline property on the input box:</li></ul><pre>.todo-form {<br>    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);<br>    <br>    <br>    &amp;__input { <br>            border: none;<br>            color: black;<br>            font-size: 1rem;<br>            padding: 0.5rem 0.5rem;<br>            display: block;<br>            background-color: #ecfaed;<br>          }<br>        &amp;__input::placeholder {<br>            color: #a6e9a8;<br>        }<br>        &amp;__input:focus {/// here <br>            outline-color: rgb(157, 167, 159); /// here<br>          }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*35orLtJCYkZADGrt6s665Q.png" /></figure><ul><li>Moving on to the list styling, we aim for a sleek, modern look for our to-do items. To achieve this, we’ve removed the default bullet points with list-style-type: none, ensuring that each item presents as a part of a cohesive design rather than a standard list. The list&#39;s background color is set to white to stand out against any other page elements, and the padding and margin are reset to eliminate any default spacing:</li></ul><pre>#todo-list {<br>    background-color: #fff;<br>    padding: 0;<br>    margin: 0;<br>    list-style-type: none;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*a5c-FA0gmW08u2qz2Tp8hQ.png" /></figure><ul><li>Each list item (li) has been given individual styling. A border is applied to the top of each item, which is 1px solid and subtly colored with #e5e5e5 to delineate them. The cursor is set to pointer to visually indicate that each item is interactive.</li><li>The font size of the list items is standardized at 1rem , which is 1rem from the 20px font we set earlier in the body. As for padding, we&#39;ve applied 0.1rem vertically (top and bottom) and 0.5rem horizontally (left and right). This slight vertical padding creates just enough space between the text and the border without making the item look too spacious.</li><li>We also changed the font to Popppins (if you want to make your life easier, since all the elements will be using Poppins font, just apply the font property to the body and it will be given to all the children elements)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*wmkucsXX6U6OwMEjCcFxqg.png" /></figure><p><strong><em>By clicking on the text of the list item, a ‘toggle’ event is fired,</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5PiGd2xEXLfZ7A_fYn1cA.png" /></figure><p>This is another instance of user interaction. When the user clicks the text, it triggers an event. In the code snippet below, we’ve attached an event listener to the list element. Upon clicking, we use the toggle method to switch the &#39;completed&#39; class on and off. This toggling action visually indicates whether a task has been completed:</p><pre>todoForm.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>  e.preventDefault();<br>  const todoEl = document.createElement(&#39;li&#39;); // Create a new &#39;li&#39; element<br>  todoEl.textContent = todoInput.value; // Set the text content of the &#39;li&#39; to the input value<br>  todoList.appendChild(todoEl); // Append the new &#39;li&#39; to the &#39;ul&#39;<br><br>  todoEl.addEventListener(&#39;click&#39;, (e) =&gt; {<br>    todoEl.classList.toggle(&#39;completed&#39;);<br>  });<br>});</pre><blockquote>Toggle a class</blockquote><blockquote>To toggle a class, we can use the toggle method. The toggle method will:</blockquote><blockquote>Add the class if the class is not present in the element.</blockquote><blockquote>Remove the class if the class is present in the element.</blockquote><blockquote>The toggle method returns true if the class is added, and false if the class is removed.</blockquote><p>To ensure our code functions correctly, we need to structure our event listeners properly. The current implementation inside the submit event listener for todoForm isn&#39;t optimal because it nests the click event listener within it. This setup could lead to multiple event listeners being attached to a single todoEl if a user submits the form multiple times. Instead, we should separate the concerns: use the submit event to create and append the new li element, and then handle the toggle functionality outside of this event. Here’s how it could be restructured:</p><pre>// Event listener for form submission<br>todoForm.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>    e.preventDefault();<br>    const todoEl = document.createElement(&#39;li&#39;); // Create a new &#39;li&#39; element<br>    todoEl.textContent = todoInput.value; // Set the text content of the &#39;li&#39; to the input value<br>    todoList.appendChild(todoEl); // Append the new &#39;li&#39; to the &#39;ul&#39;<br>    todoInput.value = &#39;&#39;; // Clear the input field after adding the to-do item<br>    <br>    // We need to ensure we&#39;re not adding multiple click event listeners to the same todoEl<br>  });<br>  <br>  // Separate event listener for toggling completion<br>  todoList.addEventListener(&#39;click&#39;, (e) =&gt; {<br>    if (e.target.matches(&#39;li&#39;)) {<br>      e.target.classList.toggle(&#39;completed&#39;);<br>    }<br>  });</pre><p>If we test the functionality as it stands, we won’t observe any visual change upon clicking a list item. This is because, although we’ve successfully toggled the ‘completed’ class on the new HTML element, we haven’t yet defined any CSS styling for list items with the ‘completed’ class. Without corresponding styles, the ‘completed’ class has no visual impact. We have to add the below to our SASS file to say when li is set to completed, this is what we expect to see:</p><pre>#todo-list li.completed {<br>    color: #b6b6b6;<br>    text-decoration: line-through;<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*SeW_NB_NKRNpktJgxQ_I1w.png" /></figure><p><strong><em>Clicking on the ‘X’ associated with a list item triggers a ‘remove’ or ‘delete’ event</em></strong></p><p>The final interaction we need to address is the functionality of the ‘X’ button/text for removing tasks. Currently, our list items lack this ‘X’ feature, so we must include it within each list element as part of its creation. The way i think about it is whenever an li element is created, a button X is added to it using append:</p><pre>todoForm.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>    e.preventDefault();<br>    const todoEl = document.createElement(&#39;li&#39;); // Create a new &#39;li&#39; element<br>    todoEl.textContent = todoInput.value; // Set the text content of the &#39;li&#39; to the input value<br>    todoList.appendChild(todoEl); // Append the new &#39;li&#39; to the &#39;ul&#39;<br>    todoInput.value = &#39;&#39;; // Clear the input field after adding the to-do item<br>    <br>    const deleteBtn = document.createElement(&#39;button&#39;); // Create the delete button<br>    deleteBtn.textContent = &#39;X&#39;; // Set the button text to &#39;X&#39;<br>    deleteBtn.className = &#39;delete-btn&#39;; // For styling<br>    deleteBtn.type = &#39;button&#39;; // Specify that this button should not submit the form // Specify that this button should not submit the form<br>    todoEl.appendChild(deleteBtn); // Append the delete button to the todo element<br><br>  });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*GOoSXuDnksT_EjnF5nelOg.png" /></figure><p>The button is now present, but it lacks functionality. The crucial next step is to enable the removal of the item upon clicking the button. “Click” is the operative term here, as we’re venturing into event handling territory. To make the button functional, we need to attach an event listener to it, ensuring it responds appropriately when interacted with:</p><pre>    deleteBtn.addEventListener(&#39;click&#39;, (e) =&gt; {<br>      todoEl.remove();<br>    });</pre><p>This code guarantees that clicking the ‘X’ button will remove its corresponding list item. To seamlessly blend the button into our design, styling adjustments are necessary. We aim to strip away the button’s border, clear its background color, and introduce a margin on the left to ensure visual harmony within its container. Achieving this involves setting the list item (li) to display: flex, which is effective for one-dimensional layouts, allowing us to easily manage horizontal spacing. To create space between the to-do text and the &#39;X&#39; button, we can utilize the justify-content: space-between property, distributing the items evenly across the available space within the list item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gw6aaVsu9YRkwFSl2cWo2A.png" /></figure><pre>  .todo-list li {<br>    border-top: 1px solid #e5e5e5;<br>    cursor: pointer;<br>    font-size: 1rem;<br>    padding: 0.1rem 0.5rem;<br>    display: flex;<br>    justify-content: space-between;<br>    align-items: center; <br>    margin-bottom: 1px; <br>  }</pre><pre>  .delete-btn {<br>    margin-left: 1px; <br>    cursor: pointer; <br>    background-color: transparent;<br>    border: none;<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*dtaJnTUAaLrRF66VF-7DtA.png" /></figure><h3>Summary:</h3><p>A to-do list might not seem like a standout portfolio project, yet it’s an excellent exercise for honing the skills essential for developing dynamic websites, particularly for beginners. Suppose you’re diving into a new programming language or technology. In that case, building a to-do list can accelerate your understanding, especially if you’re already familiar with programming concepts. This project is beneficial for reinforcing your knowledge and adapting it to different environments.</p><p>Some enhancements to consider for this project include:</p><ul><li>implementing error handling to manage incorrect user inputs and</li><li>integrating local storage to persist to-do tasks even when the user navigates away from the page.</li></ul><p>Thanks for checking this out and happy coding/working on your craft.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5db236ba708b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The DOM made simple]]></title>
            <link>https://medium.com/@castonboyd/the-dom-made-simple-1be648631ac4?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be648631ac4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[document-object-model]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 14:48:18 GMT</pubDate>
            <atom:updated>2024-03-12T17:25:17.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZseDGlKtSt5mvX0wxOiA9g.png" /></figure><p>In this article, we’re diving into the essence of the DOM and its role in enriching modern websites on any browser. Consider this a straightforward path to grasp what the DOM really is and to guide you through the process of ‘manipulating the DOM’ with confidence.</p><h3><strong>What is the DOM?</strong></h3><p>When discussing the DOM, let’s consider a statement from the W3C that sheds light on what the DOM really is, thanks to its connection with the World Wide Web Consortium:</p><blockquote>“The DOM is a W3C (World Wide Web Consortium) standard.”<br>It outlines a framework for interacting with documents: <br>“The W3C Document Object Model (DOM) is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”</blockquote><p>In essence, the DOM serves as a <strong>“standard”</strong> for how browsers should engage with documents, particularly HTML documents in our context. Picture this narrative:</p><blockquote>Imagine someone attempting to create a web browser like any other application developed out there. Indeed, the Chrome browser you use daily functions similarly to applications such as Spotify and YouTube. Spotify envelops you in a world of music, and YouTube animates videos, but what unique role does a browser play? It unlocks access to the global expanse of information, to the websites created by people everywhere.</blockquote><p>When someone develops a browser, such as Chrome, the primary function of this application is to retrieve and display HTML documents for you. Although these web pages appear styled and visually appealing, at their core, they are about delivering the information, content, and various other resources you seek on the internet. This allows you to connect with a vast array of digital experiences. I came across an illustrative image that perfectly captures what a browser is designed to do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*Tq6xYYeDMyy6ux0N.png" /></figure><p>In the depicted image, the browser requests specific information from a server, which is then returned to you as a response. When someone develops a browser, their aim is to offer the same functionality as existing browsers like Chrome and Safari. This means providing access to websites you wish to explore by typing a URL into the search box. The process isn’t arbitrary; there’s a set of<strong> <em>programmed rules</em></strong> ensuring that your experience on this new browser mirrors that of any other browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*ZseDGlKtSt5mvX0wxOiA9g.png" /></figure><p>When we talk about ‘programmed rules,’ we’re essentially saying that a browser needs to behave in a way that aligns with your expectations, just like any other app does what you anticipate it will do. Delivering interactive websites, where ‘interactive’ means you get to click, scroll, engage, and change things. This is where the DOM, or Document Object Model, comes into play. It’s what we call a <strong>‘platform’</strong> and <strong>‘language-neutral interface</strong>’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A90c-TDMeEeHOxln.png" /></figure><p>Just like Spotify is our favorite hub for music, consider the DOM as the essential system for browsers. It’s important for ensuring that when browsers, such as Google Chrome, process those HTML documents someone else has crafted — because, let’s not forget, websites are essentially files created by someone — they do so using a ‘standard’ approach. This ensures that regardless of the website you’re exploring, your experience remains consistent, interactive, and uniformly standard.</p><p><strong><em>DOM as an application</em></strong></p><p>Let’s keep exploring the DOM as both an application and a platform. The DOM is a technology that browsers leverage to transform HTML files and other documents. Imagine, if you will, the browser as a user who has the DOM installed on its device (figuratively speaking, since browsers don’t actually use phones). The browser taps into the DOM ‘app’ whenever it receives a collection of files a user has requested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVtc8ZcYOQDYZd66j1pJSg.png" /></figure><p>The DOM is essentially a platform that follows a standardized method to transform files, resulting in what we know as the DOM tree. This process is pretty complex so we wont go into the entire aspect but <a href="https://medium.com/teknasyon-engineering/what-is-the-dom-how-does-html-rendering-happen-in-browsers-cbeb12bdfea6"><strong>heres</strong></a><strong> </strong>an article if you’re curious. At its core though, it involves taking all the elements from an HTML file and converting them into programmable objects. These objects become something you can manipulate with programming languages like Python, JavaScript, or any other language. This is what the W3C refers to when they describe the DOM as a <strong>“language-neutral interface”</strong> — it’s designed to work across any programming language, making the elements of a <em>web page accessible and interactive for developers.</em> Below is an example of this:</p><pre>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;My document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Header&lt;/h1&gt;<br>  &lt;p&gt;Paragraph&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VNddkyOIXUo9rSWX.png" /></figure><p>This serves as an illustrative example to help you grasp how HTML is interconnected with its elements in a hierarchical structure that establishes node-like relationships. Below is a detailed example showcasing what’s truly happening behind the scenes (the below is an example in JS):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*WpALJjkWFdNQQTO54sakxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiwpqiN8BA1kOCnhStcArA.png" /></figure><p>The example provided above might not be the most accurate in detail, but it closely illustrates the concept. The primary aim here is to demonstrate how the DOM acts as a framework for transforming HTML into programmable objects. This transformation allows us to interact with HTML elements through code, enhancing the website’s interactivity and enabling us to do more than just style and layout.</p><p><strong><em>DOM in sum</em></strong></p><p>To summarize, the DOM acts as a critical interface that allows browsers to transform static HTML documents into dynamic, interactive web pages. It essentially converts HTML elements into programmable objects, enabling developers to manipulate these elements using code, such as Python or JavaScript. This process enhances a website’s functionality far beyond mere styling and layout, facilitating user interactions and dynamic content updates. The steps of the flow are below: <br>HTML Creation: The HTML code is written by developers. This code describes the structure and content of a webpage, including text, links, images, and other elements.</p><ol><li>Browser Interpretation: When you visit a website, your browser (e.g., Chrome, Firefox, Safari) fetches the HTML document and reads (or “parses”) it. The browser understands this HTML and knows how to process it.</li><li>DOM Model Creation: As the browser parses the HTML, it constructs the Document Object Model (DOM). The DOM is a tree-like representation of the webpage’s structure. It represents the document as nodes and objects, allowing programming languages like JavaScript to interact with the webpage’s content and structure.</li><li>Rendering: Once the DOM is built, the browser will render the webpage on the screen. This process involves calculating the layout of each element based on the DOM and the styling information from CSS. Then, the browser paints the webpage on the screen for the user to see.</li></ol><h3><strong>DOM in Action</strong></h3><p>Open your preferred code editor, such as VS Code, and create a new HTML file. Then, insert the following code snippet into the file. After adding the code, use the Live Server extension (if you have it installed) to preview the file in your web browser.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;DOM Example&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1 id=&quot;header&quot;&gt;Hello, World!&lt;/h1&gt;<br>    &lt;button id=&quot;changeTextBtn&quot;&gt;Change Text&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In preview, you should see something like this on the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*E54mbmCObpu88sHrj4Abrw.png" /></figure><p>What just occurred is twofold: when a webpage loads, the visual presentation of the HTML comes to life on your screen, showcasing the website’s layout, colors, and design as intended for the viewer. Simultaneously, behind the scenes, the HTML content is loaded into the browser as an object model, laying the foundation for how the page behaves and interacts with user inputs.</p><p><strong><em>Using the inspection tool</em></strong></p><p>If you right-click on the page you’re viewing and select “Inspect” (the shortcut is Cmd+Option+I on Mac and Ctrl+Shift+I on PC), you can navigate to the &quot;Elements&quot; tab. Here, you&#39;ll see what appears to be the HTML structure. However, remember, this is a representation created by the browser. To demonstrate this, head over to your console and enter the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfypA6pKtatpOSlbBAR5GA.png" /></figure><p>If you click enter, you will notice the following appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRIEg6hwENgdB-ucvKzC9g.png" /></figure><p>If you open up the HTMLCollection, you will notice this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdBRLn-6_VziFTKeWfyOgA.png" /></figure><p>We wont go into details everything that can be seen but in summary, this output represents an HTMLCollection, a type of object in JavaScript used to hold a collection of HTML elements from the DOM. In this particular instance, the HTMLCollection contains three elements:</p><ol><li>An &lt;h1&gt; element with the id header</li><li>A &lt;button&gt; element with the id changeTextBtn</li><li>A &lt;script&gt; element</li></ol><p>The HTMLCollection also provides named access to elements that have an id, as shown with header: h1#header and changeTextBtn: button#changeTextBtn, allowing you to directly access these elements using their ID as a property of the collection. The length property indicates the total number of elements in the collection, which is 3 in this case.</p><p><strong><em>Accessing from the browser</em></strong></p><p><em>If we wanted to access or manipulate a specific element directly from the console in the developer tools, we could use the following approach:</em></p><pre>document.getElementById(&#39;elementId&#39;);</pre><p><em>For instance, if you’re aiming to select the </em><em>&lt;h1&gt; element with the id </em><em>header, you would enter</em></p><pre>document.getElementById(&#39;header&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KynFjT_9FC1Hkdhi6gKnrQ.png" /></figure><p>This command returns the &lt;h1&gt; element, allowing you to interact with it directly from the console. You can then modify its properties, styles, or content as needed.</p><p><strong><em>Modifying from the browser</em></strong></p><p>To modify the &lt;h1&gt; element you&#39;ve selected, you can directly change its properties through the console. Here&#39;s how you might change the text content and style of the &lt;h1&gt; element with the id header:</p><pre>// Select the &lt;h1&gt; element<br>let headerElement = document.getElementById(&#39;header&#39;);<br><br>// Change the text content<br>headerElement.textContent = &#39;New Title Here!&#39;;<br><br>// Change the style, for example, color<br>headerElement.style.color = &#39;blue&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTx8JZErN19NI69EKSNWpw.png" /></figure><p>When you run these lines in the console, the &lt;h1&gt; element on the page will update to display &quot;New Title Here!&quot; in blue color. This demonstrates how you can interact with and modify webpage elements in real-time using the browser&#39;s developer tools console.</p><p><strong><em>Adding a JS file to your program</em></strong></p><p>To demonstrate modifying your webpage using an external JavaScript file, follow these steps:</p><h3>Step 1: Create a JavaScript File</h3><p>Create a new file and name it script.js using your preferred code editor, ensuring it&#39;s saved in the same directory as your HTML file. For this example, we&#39;ll focus solely on JavaScript, so we won&#39;t be adding any CSS. However, it&#39;s important to note that while CSS primarily alters the appearance of HTML content, JavaScript allows for more dynamic interaction with the HTML through programming.</p><h3>Step 2: Link the JavaScript File to Your HTML</h3><p>In your HTML file, add a &lt;script&gt; tag right before the closing &lt;/body&gt; tag to link to the script.js file. It should look like this:</p><pre>&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><h3>Step 3: Check that HTML and JS file are linked</h3><p>To ensure your app.js file is properly linked and executing in conjunction with your HTML file, insert a console log statement at the beginning of your app.js file like so:</p><pre>console.log(&quot;Hello I&#39;m from the JS file!&quot;);</pre><p>This line of code will output “Hello I’m from the JS file!” to the browser’s console, confirming that the app.js file is successfully connected and running. To view this message, open your web browser&#39;s developer tools and navigate to the console tab after loading your HTML page.</p><h3>Step 4: Write Your JavaScript Code</h3><p>Open script.js in your code editor and add the following JavaScript code:</p><pre>// Change the background color of the body<br>document.body.style.backgroundColor = &#39;lightblue&#39;;<br><br>// Change the text content of the h1 element<br>document.getElementById(&#39;header&#39;).textContent = &#39;Welcome to My Page!&#39;;<br><br>// Change the color of the h1 element<br>document.getElementById(&#39;header&#39;).style.color = &#39;darkblue&#39;;</pre><p>You have successfully executed JavaScript on the DOM. By adding code to your JavaScript file, as soon as your browser loads your webpage, it interprets the JavaScript commands and applies them to the page. This dynamic interaction modifies the webpage in real-time based on the instructions you’ve provided in the script. Whether it’s changing styles, adding content, or reacting to user actions, your JavaScript code directly influences the DOM</p><h3>More Practice</h3><p>Here are the different methods and way for manipulating the DOM with code:</p><p><strong><em>Search/Query/Read Functions</em></strong></p><ol><li>document.querySelector(selector)-Selects the first element that matches the specified CSS selector.</li></ol><pre>const firstButton = document.querySelector(&#39;button&#39;);</pre><p>2. document.querySelectorAll(selector)- Selects all elements that match the specified CSS selector and returns them as a NodeList.</p><pre>const allButtons = document.querySelectorAll(&#39;.btn&#39;);</pre><p>3. document.getElementById(id) — Selects an element by its unique ID.</p><pre>const headerElement = document.getElementById(&#39;header&#39;);</pre><p>4. document.getElementsByClassName(className)- Selects all elements that have the specified class name and returns them as an HTMLCollection.</p><pre>const highlightedTexts = document.getElementsByClassName(&#39;highlight&#39;);</pre><p>5. document.getElementsByTagName(tagName)-Selects all elements with the specified tag name.</p><pre>const allDivs = document.getElementsByTagName(&#39;div&#39;);</pre><p><strong><em>Create and Append Elements</em></strong></p><ol><li>document.createElement(tagName)- Creates a new element with the given tag name.</li></ol><pre>const newDiv = document.createElement(&#39;div&#39;);</pre><p>Explanation: This line of code creates a new &lt;div&gt; element and stores it in the variable newDiv. The element is not yet visible in the document because it has not been added to the DOM.</p><p><strong>2. parentNode.appendChild(childNode)- </strong>Appends a node as the last child of a parent node.</p><pre>document.body.appendChild(newDiv);</pre><pre>// Create a new unordered list (ul) element<br>const newList = document.createElement(&#39;ul&#39;);<br><br>// Manually create and append 3 list items (li) to the unordered list<br>for (let i = 1; i &lt;= 3; i++) {<br>    const listItem = document.createElement(&#39;li&#39;);<br>    listItem.textContent = `Item ${i}`;<br>    newList.appendChild(listItem); // Append each listItem to the newList<br>}<br><br>// Append the newList (ul) to the document body<br>document.body.appendChild(newList);</pre><p><em>Edit Elements</em></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;DOM Manipulation Examples&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div id=&quot;demo&quot;&gt;<br>        &lt;p id=&quot;text&quot;&gt;This is some text.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;button id=&quot;changeText&quot;&gt;Change Text&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now, let&#39;s use JavaScript to perform the operations listed:</p><p>1. element.innerText</p><pre>document.getElementById(&#39;text&#39;).innerText = &quot;Updated text content!&quot;;</pre><p>Changes the text inside the paragraph to &quot;Updated text content!&quot;.</p><p>2. element.innerHTML</p><pre>document.getElementById(&#39;demo&#39;).innerHTML = &#39;&lt;p&gt;New HTML content!&lt;/p&gt;&#39;;</pre><p>Replaces the content of the div with a new paragraph containing &quot;New HTML content!&quot;.</p><p>3. element.setAttribute(name, value)</p><pre>document.getElementById(&#39;changeText&#39;).setAttribute(&#39;data-status&#39;, &#39;active&#39;);</pre><p>Adds a new attribute data-status=&quot;active&quot; to the button.</p><p>4. element.getAttribute(name)</p><pre>console.log(document.getElementById(&#39;changeText&#39;).getAttribute(&#39;data-status&#39;));</pre><p>Logs the value of data-status attribute of the button, which is &quot;active&quot;.</p><p>5. element.removeAttribute(name)</p><pre>document.getElementById(&#39;changeText&#39;).removeAttribute(&#39;data-status&#39;);</pre><p>Removes the data-status attribute from the button.</p><p>6. element.style.property</p><pre>document.getElementById(&#39;text&#39;).style.color = &quot;blue&quot;;</pre><p>Changes the text color of the paragraph to blue.</p><p>7. element.classList.add(className)</p><pre>document.getElementById(&#39;text&#39;).classList.add(&#39;highlight&#39;);</pre><p>Adds the class highlight to the paragraph.</p><p>8. element.classList.remove(className)</p><pre>document.getElementById(&#39;text&#39;).classList.remove(&#39;highlight&#39;);</pre><p>Removes the highlight class from the paragraph.</p><p>9. element.classList.toggle(className)</p><pre>document.getElementById(&#39;text&#39;).classList.toggle(&#39;highlight&#39;);</pre><p>Toggles the highlight class on the paragraph, adding it if it&#39;s not there or removing it if it is.</p><p>Hopefully this is helpful. Please be on the lookout for DOM events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be648631ac4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Profile Card with HTML and CSS Grid]]></title>
            <link>https://medium.com/@castonboyd/building-a-profile-card-with-html-and-css-grid-5b1af4c3f59d?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b1af4c3f59d</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 03:08:27 GMT</pubDate>
            <atom:updated>2024-03-11T03:08:27.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*8gSSSYYe-KKPGV3Or1aojQ.png" /></figure><h3><strong>About</strong></h3><p>In this article, I’m excited to guide you through coding the profile card shown above. While there are numerous approaches one could take, I’ve chosen to leverage CSS Grid for its powerful layout capabilities. Along the way, I’ll share insights into my thought process regarding placement and styling, complemented by visuals to aid your understanding. Let’s get started.</p><h3><strong>Designing a Semantic HTML Structure</strong></h3><p>Some individuals might prefer to dive straight into coding, but I find it helpful to sketch boxes around the components of the image I’m replicating with HTML/CSS. This approach gives me a clearer understanding of how different elements will interact and positions me to start contemplating the styling aspects early on. For the image above, I’ve outlined the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*YOhgn_Uz8I4nciFwdDJ1cw.png" /></figure><p>Right off the bat, I’m recognizing that my container will encapsulate all elements, serving as the parent class. This realization prompts me to consider its positioning/display relative to its overarching container (html, body) and how its child elements will be similarly arranged. However, before we delve into those details, let’s lay out the HTML structure. Starting with the container, I’ll name it “card-container,” which will reside within the body, making the body its parent:</p><pre>&lt;body&gt;<br>    &lt;!-- card starts here --&gt;<br>    &lt;article class=&quot;card-container&quot;&gt;<br><br>    &lt;/article&gt;<br>    &lt;!-- card ends here --&gt;<br>&lt;/body&gt;</pre><p>Next, I’m turning my attention to the images that appear prominently at the top of this container box. To incorporate them, I plan to set both a background image and a profile image. Each image will be housed in its own dedicated container, as shown below:</p><pre>    &lt;!-- card starts here --&gt;<br>    &lt;article class=&quot;card-container&quot;&gt;<br>        &lt;figure class=&quot;bg-img&quot;&gt;<br>            &lt;img src=&quot;bg.png&quot; alt=&quot;background&quot; class=&quot;bg-image&quot;&gt;<br>        &lt;/figure&gt;<br>        &lt;figure class=&quot;profile-img&quot;&gt;<br>            &lt;img src=&quot;profile-picture.jpg&quot; alt=&quot;profile picture&quot; class=&quot;profile-pic&quot;&gt;<br>        &lt;/figure&gt;<br>    &lt;/article&gt;<br>    &lt;!-- card ends here --&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*C3XxQAm5pTvEITLeTLabqw.png" /></figure><p>Following the images, I notice a section dedicated to the content of the profile card. I’ll craft a container for this content, incorporating a &lt;p&gt; tag for the description and a header tag for the name.</p><pre>    &lt;article class=&quot;card-container&quot;&gt;<br>        &lt;figure class=&quot;bg-img&quot;&gt;<br>            &lt;img src=&quot;bg.png&quot; alt=&quot;background&quot; class=&quot;bg-image&quot;&gt;<br>        &lt;/figure&gt;<br>        &lt;figure class=&quot;profile-img&quot;&gt;<br>            &lt;img src=&quot;profile-picture.jpg&quot; alt=&quot;profile picture&quot; class=&quot;profile-pic&quot;&gt;<br>        &lt;/figure&gt;<br>        &lt;section class=&quot;profile-info&quot;&gt; <br>            &lt;h2 class=&quot;profile-name&quot;&gt; Jessica Randall&lt;/h2&gt;<br>            &lt;p class=&quot;profile-bio&quot;&gt; Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quae natus sed dolor nihil quam voluptas suscipit sequi, iusto quia quidem voluptates necessitatibus magnam et saepe tenetur earum sunt fugit impedit?&lt;/p&gt;<br>        &lt;/section&gt;<br>    &lt;/article&gt;</pre><p>From your live server, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtbxgGwrbWEEcRrV0cvvAQ.png" /></figure><p>To conclude, I’ll add the social links section. If you’re interested in using the same icons featured in the image, visit <a href="https://fontawesome.com/">FontAwesome</a>. You’ll find a search box similar to the one described below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ee09gC6gif8k9xlzgQVbMA.png" /></figure><p>Copy that link and add it to the head of your html file like so</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Profile Card&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;/styles/styles.css&quot;&gt;<br>    &lt;script src=&quot;https://kit.fontawesome.com/8695b27503.js&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;</pre><p>From that point, you’ll have access to a wide range of free icons. Next, you’ll need to embed them within an &lt;a&gt; tag, as these icons will serve as links to social media accounts. Considering there are approximately four to five accounts, it&#39;s advisable to group them in their own container. For semantic clarity, placing them within a &lt;nav&gt; element, with individual links for each social account, is the best approach:</p><pre>        &lt;nav class=&quot;social-links&quot;&gt;<br>            &lt;a class=&quot;fa-brands fa-facebook&quot;&gt; &lt;/a&gt;<br>            &lt;a class=&quot;fa-brands fa-instagram&quot;&gt; &lt;/a&gt;<br>            &lt;a class=&quot;fa-brands fa-whatsapp&quot;&gt; &lt;/a&gt;<br>            &lt;a class=&quot;fa-brands fa-linkedin&quot;&gt; &lt;/a&gt;<br>        &lt;/nav&gt;</pre><p>This completes the html section of our work. Your live server should render the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Laqos9GqVPgZeC8pzwQzyg.png" /></figure><h3><strong>Positioning and Styling Profile Card</strong></h3><p>I emphasize positioning and styling because it’s important to consider not only how elements appear but also their placement and relationships with other elements. My approach involves evaluating the current state of my HTML and envisioning the desired outcome. This entails methodically mapping out each element and determining the necessary steps to achieve the final output. You can see my mapping below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpwiaxg0avo5J5zPZphDEw.png" /></figure><p><strong><em>Setting a Universal Base: Aligning All Elements to the Origin</em></strong></p><p>I prefer to begin with a clean slate by setting the margins and padding to 0 and applying a border-box model to every element. I also just wanted to add the font so that it applies to all elements with text. This will not always the approach but for this project, it will be. This approach ensures that elements behave as expected when I adjust their size or make other modifications. If you’re curious about the border-box model and its benefits, I recommend reading<strong> </strong><a href="https://medium.com/@castonboyd/box-model-css-positioning-with-mondrian-style-art-754d6e94684c"><strong>this article</strong></a> to deepen your understanding.</p><pre>* {<br>    margin: 0;<br>    padding: 0;<br>    box-sizing: border-box;<br>    font-family: &#39;Poppins&#39;, &#39;sans-serif&#39;;<br>}</pre><p>Setting these adjustments will position your elements in the top left corner, as they fall under the parent class. With margins and padding set to zero for all elements, including the parent html/body that also lacks margin or padding, their initial position defaults to the coordinates 0,0, aligning them at the top left. Your rendering should look like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQIo47aThSIBEgPfkEu9UQ.png" /></figure><p><strong><em>Centralizing with HTML/Body Elements</em></strong></p><p>The HTML and Body elements serve as the core container for my card, enabling me to centralize the card and effectively manage its child components via the container class. This approach affords me control over the card’s positioning and alignment throughout the webpage. To provide a clearer distinction, I will apply a background color to the body and a white background color for the card container:</p><pre>html, body {<br>    background-color: #282828;<br>}<br>.card-container {<br>  background-color: white;<br>}</pre><p>This visual aid helps differentiate between the body — as the overarching container — and the card container, which houses all elements of the card, including the background picture, profile picture, information, and social links. The card container stretches the width of the screen and covers the content height wise which is the default for a<strong><em> block element</em></strong>. My job soon will be to make it smaller so that it looks like our exemplar.</p><p>Set html/body to the viewport (browser screen that you see)</p><p>Next, I usually define the width and height of the html/body container to ensure it spans the entire browser window, achieving the expansive coverage you observe.</p><pre>html, body {<br>    width: 100vw;<br>    height: 100vh;<br>    background-color: #282828;<br>}</pre><p>Using width: 100vw and height: 100vh for the html and body elements ensures they fill the entire viewport, providing a uniform full-screen layout. This method, akin to setting width and height to 100%, guarantees that the webpage makes use of all available screen space. Consequently, the elements inside operate within a parent container that has been allocated 100% of the viewport space, creating a scalable foundation for designing responsive layouts. This means, any child element can be sized and positioned relative to this full viewport canvas, allowing for precise control over the page layout and ensuring content is displayed consistently across different screen sizes.</p><p>Since the html/body serve as parent containers, I intend to use a grid layout for the card, the child element. Grid enables easy centering and systematic arrangement of components. If you want to learn more about grid, click <a href="https://medium.com/@castonboyd/start-simple-with-css-grid-with-mondrians-art-for-absolute-beginners-70f28a4f84a2"><strong>here</strong></a><strong>.</strong></p><pre>html, body {<br>    width: 100vw;<br>    height: 100vh;<br>    display: grid;<br>    background-color: #282828;<br>}</pre><p>Since there is only one element as a direct child of the html/body container, I need to consider just this single element in my layout template, particularly focusing on its column configuration.</p><pre>html, body {<br>    width: 100vw;<br>    height: 100vh;<br>    display: grid;<br>    grid-template-columns: 1fr;<br>    background-color: #282828;<br>}</pre><p>What you’ll observe is the container filling the entire screen, indicating that the 1fr setting is effectively allocating the full column grid space to the single element. Below is an illustration to demonstrate this concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*wrxSecoLNdMsv9B5T2Fd9A.png" /></figure><p><strong><em>Next we align-content:</em></strong></p><pre>html, body {<br>    width: 100vw;<br>    height: 100vh;<br>    display: grid;<br>    grid-template-columns: 1fr;<br>    align-content: center;<br>    background-color: #282828;<br>}</pre><p>the align-content: center; will simply ensure that this content is centered vertically, which might give the appearance of the content &quot;fitting&quot; because it occupies less vertical space, centered within a larger container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*EzqINea-_VEbImR4hfE5Jg.png" /></figure><p><strong><em>Profile Container</em></strong></p><p>Now we’re moving on to the profile container itself. Currently, it takes up 100% of the width of its parent the HTML/Body container. I want it to be a lot less than that so I’m going to give it a quarter of that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*h1PXRtJZA0cb2-MfBpo_DA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*-EOUYrba6LYnvSxVriDloQ.png" /></figure><p>I also need to center it so I have to go back to the HTML/Body element and justify items to the center:</p><pre>html, body {<br>    width: 100%;<br>    height: 100%;<br>    display: grid;<br>    grid-template-columns: 1fr;<br>    align-content: center;<br>    justify-items: center;<br>    background-color: #282828;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*pO7gYaGFedrYcdevtlkYXw.png" /></figure><p>Now, let’s recall that we’re working within the profile container, which houses all the visible content as child elements. This setup allows us to implement a grid layout, organizing these elements into a structured grid as follows:</p><pre>.card-container {<br>  background-color: white;<br>  width: 25%;<br>  display: grid;<br>  grid-template-rows: repeat(4,auto);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*gfPsBN3A5MMTasLVl83-aw.png" /></figure><p>By setting display: grid and grid-template-rows: repeat(4, auto), we&#39;ve created a distinct cell for each element, with each occupying its own row. Since the rows are set to auto, they automatically adjust to fit the size of their content. For instance, the picture of the woman occupies its own row, which resizes to match the dimensions of the picture.</p><p>A few other things to apply to the container to make it closer to the model design would be to give it a less sharp border, an more accurate background color rather than the white, and give it a background shadow. You will have to play with these styling points but what I have below gets us close:</p><pre>.container {<br>  width: 25%;<br>  display: grid;<br>  grid-template-rows: repeat(4,auto);<br>  border-radius: 1.5%;<br>  box-shadow: 0 4px 8px rgba(255, 255, 255, 0.1);<br>  background-color: rgb(238, 238, 238);<br>}</pre><p><strong><em>Background Image</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*QltyW2B4vGfemx9jK7JbTQ.png" /></figure><pre>.card-image img {<br>  width: 100%;<br>  height: 100%;<br>  border-top-left-radius: 5px;<br>  border-top-right-radius: 5px;<br>  object-fit: cover;<br>}</pre><ul><li>width: 100%; ensures that the image spans the full width of its container, allowing it to stretch across the entire grid cell it occupies.</li><li>height: 100%; similarly, this property makes the image stretch to fill the entire height of its container. In a grid context, where this image takes up a single row, setting the height to 100% ensures the image covers the whole vertical space of that row.</li><li>object-fit: cover; is really important for background images. It makes sure the image stretches to fill the space without looking stretched or squished. If the image shape doesn&#39;t exactly fit the space it&#39;s in, this setting will trim off some edges of the image so that it fills the whole area without leaving gaps</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*CjoW56bbcyar7MRokzNeOg.png" /></figure><p><strong><em>Profile image</em></strong></p><p>In our model design, the profile image appears above the background. To ensure this layering, we position the image so it always sits on top, with the background remaining underneath. This creates a visually distinct separation where the profile photo is prominently displayed against the backdrop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ob-QiE_AHgQi8snmV16oxg.png" /></figure><p>We achieve this by doing the following in CSS:</p><pre>.profile-img img {<br>  position: relative;<br>  z-index: 1;<br>}</pre><p>In this setup, position: relative; allows us to adjust the profile image&#39;s position from where it would normally be (we still have to move it with top, left, bottom, right) , and z-index: 1; makes sure this image appears on top of other elements, like the background.</p><p>I used bottom: 100%; with a margin-bottomof -20% to position it slightly below the center of the background and to remove the deep spacing between the image and the bio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*Arc6z1hdG5kgWUTjyuR9ZA.png" /></figure><pre>.profile-img img {<br>  position: relative;<br>  z-index: 1;<br>  bottom: 100%;  <br>  margin-bottom: -20%;<br>}</pre><p>Next I centered the profile image:</p><pre>.profile-img img {<br>  position: relative;<br>  z-index: 1;<br>  bottom: 110%;<br>  margin-bottom: -20%;<br>  display: block;<br>  margin-left: auto;<br>  margin-right: auto;<br>}</pre><ul><li>display: block; makes the element a block-level element, allowing it to occupy the full available width of its parent container, unlike inline elements which only take up as much width as necessary. This is necessary for horizontal centering because margin-left: auto; and margin-right: auto; only work on block-level elements.</li><li>margin-left: auto; and margin-right: auto; automatically calculate equal margins on both the left and right sides of the element, centering it within its parent container. This technique is widely used for horizontally aligning elements like images, divs, or sections in the middle of a page or container.</li></ul><p>Obviously, next step would be to apply a border-radius and a white border.</p><pre>.profile-img img {<br>  position: relative;<br>  z-index: 1;<br>  bottom: 110%;<br>  margin-bottom: -20%;<br>  display: block;<br>  margin-left: auto;<br>  margin-right: auto;<br>  border-radius: 50%;<br>  border: #fff 10px solid;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*B7l_TP-m3GEp3ID0p56kNg.png" /></figure><p><strong><em>Header on card content</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*xw0aNfIL-eitwHK9fv2I4g.png" /></figure><p>Within the third row of our grid layout, acting as a distinct container, we have the flexibility to use Flexbox or Grid for more detailed layouts. However, for our purposes, we’ll keep it straightforward. By setting the position to relative for our text element, we adjust its vertical placement to bring it closer to the profile picture directly above. The application of margin-top: -15%; reduces the gap between the profile image and the text, while text-align: center; ensures the text is aligned in the middle, creating a balanced and focused area for the profile information.</p><pre>.profile-info h2 {<br>  position: relative;<br>  font-size: 20px;<br>  text-align: center;<br>  margin-top: -15%;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*p5PtdWeTNJiGU7ogUFrFgg.png" /></figure><p>To ensure the biography content is neatly centered within its enclosing space and to create a comfortable buffer between the text and its border, we’ll apply center alignment and introduce padding.</p><pre>.profile-info p {<br>  text-align: center;<br>  padding: 2%;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*UuOoFGhERvhPFhhJOA4gdA.png" /></figure><p><strong><em>Social Links</em></strong></p><p>Same approach, center and sizing first:</p><pre>.social-links {<br>  padding: 20px;<br>  text-align: center;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*jLmr77U_EoFbu1ARRZeXIA.png" /></figure><p>Recalling the border-box model, where the content area is highlighted in blue and the padding is indicated in green, we’ve implemented a 20px padding. This adjustment ensures the links are positioned away from the screen edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*HbANv91awBxpvUOmiOiG6g.png" /></figure><pre>.social-links a {<br>  padding: 0% 5%;<br>  font-size: 2rem;<br>  color: #ED1ABE;<br>}</pre><p>We set the padding on each anchor tag in the social links container to ensure appropriate spacing between them, focusing specifically on applying padding to the right side. This deliberate choice avoids unintended spacing on the left, top, or bottom, achieving a consistent and clean layout. Your final rendering should appear as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*QqB6U5TV-JoWABT4R-rlxA.png" /></figure><h3><strong>Bonus: Hovering Links</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Umwje8u0hYbPAd448aZiow.gif" /></figure><p>To implement a hover effect, we simply apply the :hover pseudo-class to each anchor tag. Any styling defined within this state will alter the element&#39;s default appearance. For our purpose, this involves changing the font color and applying a transformation to slightly enlarge the element upon hovering.</p><pre>.social-links a:hover {<br>  color: #31006B;<br>  transform: scale(1.5);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b1af4c3f59d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Media Queries with Holy Grail Layout]]></title>
            <link>https://medium.com/@castonboyd/intro-to-media-queries-with-holy-grail-layout-032b286f010b?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/032b286f010b</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 16:43:02 GMT</pubDate>
            <atom:updated>2024-03-08T16:43:02.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPdeO6I3WV_U3AlRl0kwbA.png" /></figure><p>This is a short introduction to responsive design. In order to following along with this article, you must have the following prereq:</p><ol><li>Understanding of HTML/CSS</li><li>CSS Grid</li><li>SASS</li><li>Understanding of github</li></ol><p>Fork and clone the repo below to follow along: <br><a href="https://github.com/CastonPursuit/holyGrailRD">https://github.com/CastonPursuit/holyGrailRD</a></p><p>To begin, go to your favorite website or if you can’t think of one, go to Youtube on your desktop. Once there you should see something like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Au1aWcqcoJm6PbeqfYqRQ.png" /></figure><p>This is when the width is set to 718.</p><p>Here is another view from the phone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*qQz81cfiOvrA5XSd0viX0g.jpeg" /></figure><h3>A bit about responsive design</h3><p>You might have noticed the variation in how websites look across different devices, but unless you’re in development, it’s likely you haven’t given much thought to the adjustments made for your device. Often, the expectation is simply that websites should function smoothly and be easy to navigate, without considering the complexity behind these adjustments. This mindset is common, so as you embark on your development journey, it’s crucial to always consider how your webpages display on various devices. This is one aspect of what is known as responsive design, which entails crafting your websites to adapt seamlessly to the diverse screen sizes and orientations of your users.</p><p>Device sizes and viewport sizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*lOB0k8TMi8YKR-WurEtqJw.png" /></figure><p>Remember that there are a lot of device sizes and browsers views that need to be considered, the above image is just an example but consider these other factors as well:</p><p><strong><em>Device Sizes:</em></strong></p><ul><li>Small Smartphones: Minimum width of 320 pixels.</li><li>Larger Smartphones: Ranging from 360 pixels to 480 pixels in width.</li></ul><p><strong><em>Tablets:</em></strong></p><ul><li>Portrait orientation: Approximately 600 pixels to 800 pixels in width.</li><li>Landscape orientation: Approximately 800 pixels to 1024 pixels in width.</li><li>Laptops and Small Desktops: Common widths include 1024 pixels, 1280 pixels, and 1366 pixels.</li><li>Large Desktop Monitors: Widths can exceed 1920 pixels, with some screens reaching up to 2560 pixels and beyond.</li></ul><p><strong><em>Major Web Browsers:</em></strong></p><ul><li>Chrome: The most widely used browser, known for its fast performance and web standards support.</li><li>Firefox: Popular for its privacy features and developer tools.</li><li>Safari: Default browser on Apple devices, prioritizing energy efficiency and privacy.</li><li>Edge: Microsoft’s browser, built on the Chromium engine, offering good performance and compatibility.</li></ul><p>This is a consideration that needs careful planning and attention before, during, and after the design phase of any website to ensure optimal performance, accessibility, and user experience across all devices and browsers. By incorporating responsive design principles from the outset and continuously testing and adjusting your site as it evolves, you can create a seamless experience for your users, regardless of how they choose to access your content.</p><h3><strong>Media Queries</strong></h3><p>Let’s delve into the concept of media queries, a crucial tool in the arsenal of responsive web design. Media queries empower web developers to create adaptable designs that respond to various screen sizes and conditions. Essentially, they allow us to apply CSS rules selectively, based on the characteristics of the device displaying the website. This capability is key to ensuring that a site is as user-friendly on a smartphone as it is on a desktop computer, optimizing layouts, fonts, and even colors for different viewing contexts.</p><p>Consider a scenario where a website’s navigation sidebar changes color as you adjust the browser’s size. This is media queries in action. They monitor the browser’s environment, such as its width, and trigger specific style changes when certain conditions are met. Through a practical example, we’ll explore how to use media queries to dynamically alter the appearance of a site element — like a sidebar or navigation menu — based on the viewport size.</p><p>Let’s add the below to our scss file underneath all our code:</p><pre>@media (max-width: 600px) {<br>   aside {<br>    background-color: brown;<br>   }<br>}</pre><p>The media query @media (max-width: 600px) means that the CSS rules contained within it will apply to screens that are 600 pixels wide or smaller. Essentially, it sets a condition: &quot;If the viewport (the visible area of a webpage) is 600 pixels wide or less, then apply the following styles.</p><p>This CSS rule is saying: “For screens that are up to 600 pixels wide, the aside element should have a brown background color.&quot; The rule remains in effect for any screen size 600 pixels wide or smaller. Once the screen width exceeds 600 pixels, this rule no longer applies, and the aside element will revert to its background color defined outside this media query or to the default if none is specified.</p><pre>@media (min-width: 471px) { <br>    footer {<br>        background-color: green;<br>    }<br><br>}</pre><p>This rule is saying: “For screens that are 471 pixels wide or wider, the footer element should have a green background color.&quot; This style will remain in effect for any screen size that meets or exceeds 471 pixels in width.</p><p>I hope this was helpful. There is much more to explore with media queries like stacking but we will handle that in another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=032b286f010b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Start Simple with CSS Grid with Mondrian’s Art for Absolute Beginners]]></title>
            <link>https://medium.com/@castonboyd/start-simple-with-css-grid-with-mondrians-art-for-absolute-beginners-70f28a4f84a2?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/70f28a4f84a2</guid>
            <category><![CDATA[website-design]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[grid-layout]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 16:55:54 GMT</pubDate>
            <atom:updated>2024-03-06T16:55:54.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*eo3idbKBbt1JMpc_QQn1Zw.png" /><figcaption>By me on repl.it</figcaption></figure><h3>About</h3><p>Layouts play a pivotal role in crafting websites, offering both structure and beauty to our online spaces. In this article, we’ll dive into an accessible approach to designing website layouts using CSS Grid. We’ll begin by unraveling the fundamental concepts behind CSS Grid creation. Then, taking inspiration from the iconic Mondrian Art, we will apply these principles to construct a piece of art ourselves using CSS grid to guide us. In order to get started, you need a basic understanding of HTML/CSS.</p><h3>Intro:</h3><p>Whenever we visit a website, its layout is the first thing we notice. Creating such well-structured online spaces is quite a challenge due to the complex nature of web layouts. Among them, the ‘holy grail’ layout is particularly noteworthy for its design sophistication and functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPgefHYQxCgMc1sxva1s3A.png" /></figure><p>However, there’s a vast array of patterns found across different websites. For web developers and designers, organizing content across various page sections is a fundamental task. This organization is achieved through styling, which structures the content effectively. Historically, positioning elements on the screen involved a few key techniques. Initially, CSS floats were commonly used, followed by the adoption of Flexbox for more flexible layouts. Today, CSS Grid has become the preferred choice for many developers, offering unparalleled control and versatility in layout design. Let’s take a closer look at how CSS Grid operates and explore its capabilities.</p><h3><strong>Example 1:</strong></h3><p>Before we dive into the intricacies of CSS Grid, let’s set up a basic HTML and CSS foundation to apply our learning. Below, you’ll find an example of a div element acting as a parent container with the class name parent, and within it, six child div elements, each containing a paragraph tag. This setup is assumed to be placed within the body of an HTML file:</p><pre>&lt;div class=&quot;parent&quot;&gt; <br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><p>For our css, all we have is the below applied:</p><pre>html {<br>  height: 100%;<br>  width: 100%;<br>}<br><br>.item {<br>  background-color: lightgray;<br>  border: 2px solid black;<br>  <br>}</pre><p>What we should see are six elements stacked on top of each other, arranged in the standard default layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fREb8Kk0M_tPSnWIRK62g.png" /></figure><p><strong><em>Applying CSS grid to the parent</em></strong></p><p>To transform the default layout above into a grid, we simply change the display property to ‘grid’. Then, we specify the number of columns we want by using the grid-template-columns property. For example, to create three columns of equal width, the syntax would be: grid-template-columns: 33% 33% 33%;:</p><pre>html {<br>  height: 100%;<br>  width: 100%;<br>}<br><br>.parent {<br>  display: grid;<br>  grid-template-columns: 33% 33% 33%;<br>}<br><br><br>.item {<br>  background-color: lightgray;<br>  border: 2px solid black;<br>  <br>}</pre><p>Once you try this, you would have notice that your grid looks like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7JK9g2nhyJYhYuY_AgZ5w.png" /></figure><p>Your default layout has now been transformed into a 2D grid with rows and columns, with each of your child elements automatically placed in its own cell. Indeed, each element really is in its own distinct cell. To further observe this, you can:</p><ol><li>Open the inspector in your browser.</li><li>Navigate to the ‘Layout’ panel.</li><li>Check the options you wish to enable, such as ‘Show Track Sizes’ for displaying grid options.</li><li>Then, look for ‘Grid Overlays’ and select the parent div container where the grid was applied.</li></ol><p>Here’s my setup in replit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGiVbmu3WjdTJvgEKr-Jwg.png" /></figure><p>This really covers the basics, or the barebones, of using CSS Grid, but there’s a lot more you to it. For instance, if we want to create some space between the items on the grid, we can use the gap property. By applying gap, we introduce space between the grid items.</p><p>At this point, you might have noticed that our items are stretching beyond their intended bounds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6DvUIC785kfSrWJq8lBIA.png" /></figure><p>A common practice in CSS Grid is to use the fr unit, which allows columns to be sized in proportion to the viewport&#39;s size.</p><p>Here&#39;s an example</p><pre>html {<br>  height: 100%;<br>  width: 100%;<br>}<br><br>.parent {<br>  display: grid;<br>  grid-template-columns: 1fr 1fr 1fr;<br>  gap: 20px; <br>}<br><br><br>.item {<br>  background-color: lightgray;<br>  border: 2px solid black;<br>}</pre><blockquote>When we say that <em>1fr</em> represents a fraction of the available space in the CSS Grid container, it means that the space inside the container is divided into parts based on the <em>fr</em> values assigned to the grid tracks (columns or rows). The available space is the total space inside the grid container minus any space taken up by margins, padding, or fixed-size tracks defined in other units (like pixels or percentages).</blockquote><blockquote>For <em>1fr</em>: It signifies that a column or row should take up one share of the available space. If all tracks are set to <em>1fr</em>, the space is divided equally among them.</blockquote><blockquote>For <em>2fr</em>: This means that a column or row is allocated two shares of the available space. So, for example, if one track is <em>1fr</em> and another is <em>2fr</em>, the second track will be twice as wide (for columns) or tall (for rows) as the first, because it&#39;s taking up twice as many fractions of the available space.</blockquote><p>Now try doing the below:</p><pre>html {<br>  height: 100%;<br>  width: 100%;<br>}<br><br>.parent {<br>  display: grid;<br>  grid-template-columns: 2fr 1fr 1fr;<br>  gap: 20px; <br>}<br><br>.item {<br>  background-color: lightgray;<br>  border: 2px solid black;<br>}</pre><p>What you may have observed is that the first column, assigned 2fr, is now twice as wide as the other columns. Experiment with varying fr values to explore how they affect the layout. Dive in, experiment, and embrace your inner engineer.</p><p><strong><em>Row and Columns in CSS Grid</em></strong></p><p>The beauty of CSS Grid lies in its automatic placement of elements across columns and rows. Suppose we modify our previous scenario by removing one element, reducing our total from six to five.</p><pre>  &lt;div class=&quot;parent&quot;&gt; <br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;item&quot;&gt; <br>      &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing.&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGE4NlX5tXFUfouawc6WwA.png" /></figure><p>This adjustment showcases CSS Grid’s flexibility in handling an uneven number of elements.</p><p><strong><em>Managing cells and spanning a cell across a full row</em></strong></p><p>Now lets say I wanted to increase the font size of the top left cell.<br>To increase the font size of the top-left cell, simply target it using its selector. In the case since all selectors have the same name, you can use the :nth-child(1) selector on the parent class like this:</p><pre>html {<br>  height: 100%;<br>  width: 100%;<br>}<br><br>.parent {<br>  display: grid;<br>  grid-template-columns: 1fr 1fr 1fr;<br>  gap: 20px;<br>}<br><br>.item p {<br>  margin: 0;<br>}<br><br>.item {<br>  background-color: lightgray;<br>  border: 2px solid black;<br>  padding: 20px;<br>  font-size: 0.7rem;<br>  line-height: 1.7;<br>}<br><br>.item:nth-child(1) {<br>  font-size: 1.1rem; <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgKW-iTvi3wO0TXvwR-G0w.png" /></figure><p>If you’ve noticed, the font size in the top-left cell has been increased to 1.1rem. This demonstrates the flexibility within CSS Grid, allowing for individual element modifications while maintaining the overall structure.</p><p>Suppose we want the top-left cell to extend across the entire row, achieving this necessitates using a span. For those who may not be familiar, span in CSS Grid terminology allows us to dictate how many rows or columns a cell should occupy. For instance, if we wish for our top-left cell to occupy two rows instead of one, we would apply grid-row: span 2; in our CSS. This directive ensures the cell expands to cover the space of two rows</p><pre>.item:nth-child(1) {<br>  font-size: 1.1rem;<br>  grid-row: span 2; <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4N6Mh2Bk5DNewfDG6Tz6g.png" /></figure><p>I can also turn the item itself into a grid and center the contents as well.</p><pre>.item:nth-child(1) {<br>  font-size: 1.1rem;<br>  grid-row: span 2;<br>  display: grid; <br>  align-content: center; <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jNQsIX2L_qCG0ASU-H-bg.png" /></figure><p>Understand that each cell within the grid can be individually adjusted to meet specific requirements, enabling the creation of intricate and customized layouts.</p><p><strong><em>Mixing Values</em></strong></p><p>You can also utilize mixed values with grid-template-columns, as shown below, where we specify 500px 1fr 1fr. This means we want the far-left column to be 500px wide, and the remaining space is divided equally between the other two columns.</p><pre>.parent {<br>  display: grid;<br>  grid-template-columns: 500px 1fr 1fr;<br>  gap: 20px;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMBMqiwnTMKoHQsdqAdKsw.png" /></figure><p><strong><em>Grid Line-based Placement</em></strong></p><p>In the context of CSS Grid, adjusting an element’s row span to 1 / 3 signifies a technical modification where the element is configured to stretch from the grid&#39;s first row line to the third, effectively covering two grid rows. This precise control allows for dynamic layout adjustments, enabling designers to specify exactly how content should flow and occupy space within the grid structure, showcasing the powerful flexibility inherent in CSS Grid for complex layout designs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*XyGOqExFf76SZF6x.png" /></figure><p>The technique of specifying how an element spans multiple rows or columns in a CSS Grid layout is known as “Grid Line-based Placement.” This method involves defining an item’s start and end positions along the grid lines, allowing for precise control over the item’s placement and span within the grid.</p><pre>.item:nth-child(1) {<br>  font-size: 1.1rem;<br>  grid-row: 1/3;<br>  align-content: center; <br>}</pre><p>For our example, it would look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1A_f1P-PfEKZRyYrKVz_kA.png" /></figure><p>Using CSS Grid is quite straightforward, as demonstrated. By wrapping elements in a parent container and setting its display to grid, the elements automatically arrange themselves in a 2D format. This setup allows us to manipulate the cells within the grid as needed, utilizing properties like grid-row, span, and grid-template-columns, among others. I encourage you to spend some time practicing these concepts. Now, let&#39;s transition to the abstract art portion of this article, where we&#39;ll apply what we&#39;ve learned in a creative context.</p><h3><strong>Abstract Art Practice</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*eo3idbKBbt1JMpc_QQn1Zw.png" /></figure><p>Here is some prework that I did and I recommend for you:</p><p>Below I have images of the grid lines i drew up for being able to visual the number of rows and colums for my grid. Then i labeled each cell in the grid. One thing that is missing are numbers to figure out how much space any particualr cell would take based on the image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1g37fIn2NqicG1ZsbBexPw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxE_XA9CWuVPsbsnhPX6sw.png" /></figure><p>Here is the HTML/CSS:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;<br>  &lt;title&gt;replit&lt;/title&gt;<br>  &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;div class=&quot;parent&quot;&gt;<br>    &lt;div class=&quot;grid-item one_red&quot;&gt; &lt;/div&gt;<br>    &lt;div class=&quot;grid-item two_white&quot;&gt;  &lt;/div&gt;<br>    &lt;div class=&quot;grid-item three_white&quot;&gt; &lt;/div&gt;<br>    &lt;div class=&quot;grid-item four_white&quot;&gt; &lt;/div&gt;<br>    &lt;div class=&quot;grid-item five_yellow&quot;&gt;  &lt;/div&gt;<br>    &lt;div class=&quot;grid-item six_white&quot;&gt;  &lt;/div&gt;<br>    &lt;div class=&quot;grid-item seven_blue&quot;&gt;  &lt;/div&gt;<br>    &lt;div class=&quot;grid-item eight_white&quot;&gt; &lt;/div&gt;<br>    &lt;div class=&quot;grid-item nine_white&quot;&gt;&lt;/div&gt;<br><br>  &lt;/div&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><pre>html, body {<br>  height: 100%;<br>  width: 100%;<br>  position: relative;<br>}<br><br>.parent {<br>  position: absolute;<br>  top: 10%;<br>  left: 10%;<br>  height: 75%;<br>  width: 75%;<br>  display: grid;<br>  grid-template-columns: 10% 30% 30% 30%;<br>  grid-template-rows: 40% 25% 25% 10%;<br>  border: 5px solid black; <br>}<br><br>.grid-item {<br>  background-color: lightgray;<br>  border: 5px black solid;<br>}<br><br>.grid-item.one_red {<br>  background-color: #B33A27;<br>  grid-column: 1 / 3;<br>  grid-row: 1 / 2;<br>}<br><br>.grid-item.two_white {<br>  background-color: #F6F5F6;<br>  grid-column: 3 / 5;<br>  grid-row: 1 / 2;<br>}<br><br>.grid-item.three_white {<br>  background-color: #F6F5F6;<br>  grid-column: 1 / 3;<br>  grid-row: 2 / 3;<br>}<br><br>.grid-item.four_white {<br>  background-color: #F6F5F6;<br>  grid-column: 3 / 5;<br>  grid-row: 2 / 3;<br>}<br><br>.grid-item.five_yellow {<br>  background-color: #F0C432;<br>  grid-column: 1 / 2;<br>  grid-row: 3 / 5;<br>}<br><br>.grid-item.six_white {<br>  background-color: #F6F5F6;<br>  grid-column: 2 / 3;<br>  grid-row: 3 / 5;<br>}<br><br>.grid-item.seven_blue {<br>  background-color: #2C395E;<br>  grid-column: 3 / 4;<br>  grid-row: 3 / 4;<br>}<br><br>.grid-item.eight_white {<br>  background-color: #F6F5F6;<br>  grid-column: 4 / 5;<br>  grid-row: 3 / 5;<br>}<br><br>.grid-item.nine_white {<br>  background-color: #F6F5F6;<br>  grid-column: 3 / 4;<br>  grid-row: 4 / 5;<br>}</pre><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70f28a4f84a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Box Model/CSS Positioning With Mondrian Style Art]]></title>
            <link>https://medium.com/@castonboyd/box-model-css-positioning-with-mondrian-style-art-754d6e94684c?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/754d6e94684c</guid>
            <category><![CDATA[website]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 15:48:28 GMT</pubDate>
            <atom:updated>2024-03-05T00:21:07.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9lY4C2Im2maCrN32il_Cw.png" /><figcaption>A digital rendition of <strong>Composition with Red Blue and Yellow Painting</strong> by Piet Mondrian</figcaption></figure><h3>About this Article</h3><p>When encountering something new, it’s natural to question its purpose and origins. Everything we interact with has been intentionally designed, reflecting a specific need or idea. This perspective is helpful when considering the digital transformation of real-world elements into web interfaces. By examining the <strong>CSS box model</strong> and <strong>positioning,</strong> we gain insights into the foundational techniques that make websites accessible and engaging for users. To illustrate the practical application of these concepts, we create a Mondrian abstract with CSS</p><p><strong>What is the CSS Box Model?</strong></p><p>The CSS Box Model is a box that wraps around every HTML element. It consists of four distinct parts: the content, padding, border, and margin.</p><p>You know that body tag we use to put all of the html content? That, at its core, is wrapped in a box. The p tag element that as well. All of these elements have the ability to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*g5ErXma_Q25C2mAr.jpg" /></figure><ol><li>Padding: The space between the content and the border.</li><li>Border: A line that goes around the padding and content.</li><li>Margin: The space outside the border.</li></ol><p>Everything on a page, including the body, is a box with all the above parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*IFXZjKhoE-bUpPjK.png" /></figure><p>You try playing around. Do the following steps to see the box model in action:</p><ol><li>Go to terminal</li><li>Make a new directory called BoxModelPractice using mkdir</li><li>cd into BoxModelPractice</li><li>code . so you can open that folder in VS code</li><li>create a new index.html</li><li>Open index.html: Ensure index.html is open in your Visual Studio Code editor.</li><li>Add Basic HTML Structure: If your index.html file is empty, start by adding the basic HTML5 document structure. You can quickly generate this by typing ! and pressing Tab if you have Emmet abbreviations enabled in VS Code. This will create the essential HTML boilerplate code.</li><li>Write the div Element: Inside the &lt;body&gt; tag of your HTML document, add a div element with the text &quot;Hello World&quot; inside it. Your index.html and cssfiles should look something like this:</li></ol><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Box Model Practice&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div&gt;Hello World&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>div {<br>        background-color: lightgray; /* Background color */<br>        border: 2px solid black; /* Border */<br>        padding: 20px; /* Padding around the text */<br>        margin: 10px; /* Margin around the div */<br>    }</pre><p><strong>Preview Your Work:</strong> To see your “Hello World” div in action, save your index.html file and open it in a web browser. You can usually do this by right-clicking the file in VS Code&#39;s explorer panel and selecting &quot;Open with Live Server&quot; if you have the Live Server extension installed, or simply by double-clicking the index.html file in your file explorer to open it with your default web browser.</p><p><strong>Experiment and Learn: </strong>From here, you can experiment with different CSS properties related to the Box Model (like width, height, border-radius, etc.) to see how they affect the appearance of your div. This hands-on practice will deepen your understanding of the Box Model concept.</p><h3>Content Box vs Border Box</h3><p>When you pop open the dev tools and start inspecting elements, you’ll quickly notice something interesting when you tweak the width. As you dial up the width, it’s not just the content area that expands; the padding, borders, and margins stack on top, bulking up the total width more than you might have asked for.</p><p>This becomes a bit of a headache when you’re trying to fit elements into a precise layout. Let’s say you’ve got this design that’s just so, and then the additional padding and borders throw your measurements off kilter.</p><p>This is where the concept of box-sizing swoops in to save the day. By default, elements use what&#39;s called the content-box model. This means if you set an element to be 100px wide, that&#39;s the width of the content itself, not including padding or borders. So, if you add a 5px border and 10px padding, your element&#39;s total width isn&#39;t 100px anymore; it&#39;s 130px (100px content + 20px padding + 10px border).</p><p>But, switch that setting to border-box, and the game changes. Now, when you set an element to 100px width, that&#39;s the final size. Padding and borders are included within that width, not added on, making it way easier to plan your layout without needing a calculator by your side.</p><p>To really nail this concept down, let’s pit two divs against each other. One&#39;s playing by the content-box rules, and the other&#39;s rocking the border-box lifestyle. By comparing these side by side, you&#39;ll see how much smoother layout planning can be when you don&#39;t have to account for extra pixels added by padding and borders. This way, what you set is what you get, making your CSS much more predictable and your layouts crisp and clean.</p><p>So, that’s the box model in essence. It’s when every element on your page comes with its own set of invisible boundaries that dictate spacing and sizing. Grasping the difference between content-box and border-box is really important because it affects the total size of your elements and your entire layout. This understanding can simplify your CSS work, making your designs more predictable and easier to manage.</p><h3>Document Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mWuIy-WEy59roX97" /></figure><p>If we delve into the structure of a typical website layout, as seen above, you’ll notice it comprises various elements or “boxes.” If you take a moment to count, you’ll find there are five distinct “boxes”. This observation underscores the fact that elements do not exist in isolation on a screen; rather, they are placed next to each other, often separated by margins for clarity and aesthetic appeal. As a web developer, orchestrating these elements to lay out in a specific manner is part of your craft.</p><p>To put this into practice, let’s start with an experiment involving div elements, which are block-level elements by default. When you create two divs, you&#39;ll observe that they stack vertically on top of each other. This is because block-level elements naturally consume the full width available to them and start on a new line.</p><pre>&lt;div&gt;First div&lt;/div&gt;<br>&lt;div&gt;Second div&lt;/div&gt;</pre><p>Not every element, however, stacks on top of each other; some are arranged horizontally. This behavior is characteristic of what we call inline elements. Here’s an example to illustrate this concept:</p><pre>&lt;span&gt;First inline element,&lt;/span&gt; <br>&lt;span&gt;Second inline element&lt;/span&gt;</pre><p>In this case, &lt;span&gt; elements are used, which are inherently inline. Unlike block-level elements like &lt;div&gt; that take up the full width available and start on a new line, inline elements only occupy as much width as their content requires and sit next to each other on the same line. This feature is particularly useful for styling text or grouping small chunks of content without breaking the flow of a document.</p><p>For a clearer demonstration, consider anchor tags (&lt;a&gt;), another common type of inline element:</p><pre>&lt;a href=&quot;#&quot;&gt;First link&lt;/a&gt; <br>&lt;a href=&quot;#&quot;&gt;Second link&lt;/a&gt;</pre><h3>Default Position for Websites</h3><p>In HTML, the default positioning of elements, when no explicit CSS positioning is applied, is static. This means elements are laid out in the order they appear in the document flow. With static positioning, elements stack naturally on the page according to their placement in the HTML markup, and properties like top, right, bottom, left, and have no effect on them.</p><p>This default behavior ensures a straightforward, linear layout of elements, from block-level elements stacking vertically to inline elements lining up horizontally next to each other, based on their order in the code.</p><p>Our task is to harness and modify this default behavior to craft modern websites for our clients, companies, or personal projects. We achieve this by utilizing the position property in CSS. While the default static positioning doesn&#39;t permit us to move an element out of its normal document flow, there are several other positioning strategies that do, allowing for more flexibility and control in our designs. These include:</p><ul><li>Relative: This allows us to move an element relative to its normal position, without altering the layout space it occupies.</li><li>Absolute: Positions an element absolutely to its nearest positioned ancestor, effectively removing it from the normal document flow.</li><li>Fixed: Fixes an element’s position relative to the viewport, making it stay in the same place even when the page is scrolled.</li><li>Sticky: A hybrid of relative and fixed positioning, where an element is treated as relative until it crosses a specified point, then it becomes fixed.</li></ul><h3>Relative Position</h3><p>Relative Positioning is about tweaking an element’s position without affecting the space it occupies in the normal document flow. When you apply position: relative; to an element, you can then use top, right, bottom, and left properties to move it from its original location. However, it&#39;s important to note that the element still occupies the same space in the document as if it hadn&#39;t been moved, meaning other elements don&#39;t adjust to fill or make space for its new position.</p><p>Let’s illustrate an example of relative positioning by showing how to move one box relative to its original position, while keeping another box static for comparison. We’ll start with some simple HTML and CSS.</p><pre>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;<br>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;<br>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;<br>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;</pre><pre>&lt;div class=&quot;box-1&quot;&gt;  &lt;/div&gt;<br>&lt;div class=&quot;box-2&quot;&gt;  &lt;/div&gt;</pre><pre>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;<br>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;<br>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;<br>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/p&gt;</pre><p><strong><em>Static Position</em></strong></p><pre>.box-1 {<br>  width: 200px;<br>  height: 100px;<br>  background-color: coral;<br>  position: static;<br>  top: 100px<br>}</pre><p>When an element is positioned statically, it adheres to the natural document flow, meaning you cannot use positioning properties like top, right, bottom, or left to move it. This default behavior ensures the layout is predictable but offers limited flexibility for precise positioning adjustments.</p><p>Try it for yourself.</p><p><strong><em>Relative Position</em></strong></p><p>Let try changing the postion to relative to …</p><pre>.box-1 {<br>  width: 200px;<br>  height: 100px;<br>  background-color: coral;<br>  position: relative;<br>  top: 100px<br>}</pre><p>Upon transitioning .box-1 to a relative position and nudging it 100px down, the space where .box-1 was initially positioned behaves as if the box is still there. This space does not collapse; it remains, preserving the layout&#39;s integrity as though .box-1 hadn&#39;t moved. This is a fundamental aspect of relative positioning: while the element moves visually, its original spot in the document flow is maintained as a placeholder, preventing other content from filling in. This behavior contrasts sharply with absolute positioning, where moving an element does cause the space it occupied to collapse, as the element is removed from the normal document flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BJgryasvJOJb8O0xq9xKQ.png" /></figure><p><strong><em>Absolute Position</em></strong></p><p>Now, if we change the position of our element to absolute, the behavior and impact on the layout are markedly different. With position: absolute;, the element is removed from the normal document flow. This means it no longer occupies space in the layout as it did before, which can lead to a noticeable shift in the surrounding content—often referred to as collapsing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6H90f_IsytboJ3nbiFekgQ.png" /></figure><p><strong><em>What happens with absolute positioning?</em></strong></p><p>When an element is set to absolute positioning, it is positioned in relation to its nearest positioned ancestor—that is, the closest ancestor element with a position property set to anything other than static (such as relative, absolute, fixed, or sticky). This means the absolutely positioned element&#39;s placement (using the top, bottom, left, and right properties) is calculated based on the dimensions and position of that ancestor.</p><p>If there is no such positioned ancestor in the element’s hierarchy, the absolutely positioned element <em>defaults to being placed relative to the initial containing block. The initial containing block is typically the viewport or the document body.</em> This is a key concept because it determines how and where the absolutely positioned element will appear on the page.</p><p>For example, if you have a div element with position: absolute; and it&#39;s contained within another div that has position: relative;, the child div will be positioned absolutely in relation to the boundaries of its parent. However, if the parent div does not have a position set, or is set to static (the default), the child div will position itself absolutely in relation to the entire document or viewport.</p><h3>Summary of box model and CSS positioning</h3><p>Every HTML element is essentially a box with various components that dictate its appearance and layout on a webpage. Altering an element’s dimensions usually affects its content area, inadvertently increasing the overall size due to padding and borders. Switching the box-sizing attribute to border-box, however, changes this dynamic, allowing the element&#39;s total dimensions to encompass padding and borders, thus maintaining the intended size.</p><p>However, these elements don’t exist in isolation; they coexist and interact with other elements on the page. This interaction highlights the importance of understanding positioning, which plays a significant role in how elements are arranged and displayed. The concepts of static, relative, and absolute positioning are key to manipulating element placement. To deepen your grasp of these concepts, you’ll create a page that serves as a canvas for experimenting with these layout techniques, offering a practical way to explore and understand the intricacies of CSS positioning and the box model.</p><h3>Explore CSS positioning with Modrian Art Page</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9lY4C2Im2maCrN32il_Cw.png" /><figcaption>A digital rendition of <strong>Composition with Red Blue and Yellow Painting</strong> by Piet Mondrian</figcaption></figure><p>In this section of the article, we’ll dedicate time to constructing the image mentioned earlier, leveraging our knowledge of CSS positioning and the box model. To begin, let’s first identify the various boxes depicted in this image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_WvE3-90yrGS2NseImnUg.png" /></figure><p>There are approximately 8 to 9 boxes in total. Each box corresponds to an element displayed on the screen.</p><p>Before diving into the coding process, I’ve decided to assign class names to each box based on a screenshot of the webpage we’re recreating. This step will allow me to precisely adjust their positioning later, as I’ll have a clear reference to which element I’m modifying by matching the class names to the labels I’ve placed on my mockup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQONv5kFtWFrtuNwdJj3-Q.png" /></figure><p>I’m also considering the space each element occupies to estimate their width and height, as well as to anticipate their potential positions in terms of top, left, bottom, or right alignments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0ccmu0abR-1mx8HWLCTGA.png" /></figure><p>Im doing all of this before I even considering HTML/CSS. I want to know the nature of my layout and discover what type of positionng and css tools i need to use in order to achieve my goal.</p><p>I’m undertaking all these steps even before diving into HTML/CSS. My aim is to thoroughly understand the layout’s nature and identify the types of positioning and CSS techniques required to achieve my desired outcome.</p><h3>HTML for Modrian Art Page</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_WvE3-90yrGS2NseImnUg.png" /></figure><p>Looking at the image again (which might require some time if you’re working through this by yourself), we notice a container with several boxes inside. This observation suggests the need for a parent class encompassing all other boxes as its children. This consideration is particularly useful when reflecting on relative and absolute positioning. While absolute positioning removes an element from the normal document flow, positioning a child element in relation to a parent (ancestor) element can effectively manage its placement. Refer to the image below for clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*BdTkBs_eizX3iHXx.PNG" /><figcaption>Image from W3School</figcaption></figure><p>Remember also to properly configure your container at the outset, setting its positioning to relative. This step is crucial as it enables the container to act as an ancestor for any contained element that is positioned absolutely.</p><pre>&lt;div class=&quot;container&quot;&gt; <br>       <br>    &lt;/div&gt;</pre><pre>*{<br>    margin: 0;<br>    padding:0;<br>    box-sizing: border-box;<br>}</pre><pre>.container {<br>    min-height: 95vh;<br>    background-color: white;<br>    margin: 20px;<br>    border: black solid 10px;<br>    position: relative;<br>}</pre><p>Let’s start by situating each element inside a container, for example, box_one_white, ensuring it&#39;s placed accurately according to the class name selectors we previously defined.</p><pre>&lt;div class=&quot;container&quot;&gt; <br>        &lt;div class=&quot;box_one_white&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;</pre><p>Let’s apply position: absolute to position the elements based on our earlier estimations. Feel free to experiment with this to gain more practice and familiarity.</p><pre>*{<br>    margin: 0;<br>    padding:0;<br>    box-sizing: border-box;<br>}</pre><pre>.container {<br>    min-height: 95vh;<br>    background-color: white;<br>    margin: 20px;<br>    border: black solid 10px;<br>    position: relative;<br>}<br></pre><pre>.box_one_white {<br>    position: absolute;<br>    background-color: #D3CEC5;<br>    height: 40%;<br>    width: 20%;<br>    border: 10px solid black;<br>}</pre><p>Continue applying the same process we used for box_one_whiteto the rest of the elements on your own. Gradually work through each one, implementing the positioning and alignment techniques we’ve discussed, until your page closely resembles the layout shown in the provided screenshot.</p><h3>Center the name box in the document</h3><p>To center an element perfectly within its parent, you can apply a combination of CSS properties that leverage absolute positioning and the transform property. Here’s a concise guide using the .name_box class as an example:</p><ol><li>Positioning: First, set the element’s position to absolute. This removes it from the normal document flow and allows it to be positioned relative to its nearest positioned ancestor.</li><li>Centering Coordinates: Next, align the element to the exact center by setting both top and left properties to 50%. This moves the top left corner of the element to the center of the parent.</li><li>Offset Adjustment: However, this approach alone will place the element’s top-left corner at the center, not the element itself. To truly center the element, apply a transform with translate(-50%, -50%). This adjusts the element back by half of its own width and height, aligning its center with the parent&#39;s center.</li><li>Styling: Add any additional styles you need, such as border, padding, background-color, font-family, and font-size to enhance the visual appearance of the centered element.</li></ol><h3>Conclusion</h3><p>That concludes our practice session on box modeling and positioning with CSS. Hopefully, this has given you a solid understanding of how web pages are structured and the ways in which elements within them can be manipulated and positioned to create effective and visually appealing layouts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=754d6e94684c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro To CSS Selectors With A Neumorphic Designed Form]]></title>
            <link>https://medium.com/@castonboyd/intro-to-css-selectors-with-a-neumorphic-designed-form-4fa9289a81e1?source=rss-2b0726ff8551------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa9289a81e1</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <dc:creator><![CDATA[Caston Boyd]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 14:42:41 GMT</pubDate>
            <atom:updated>2024-03-01T14:42:41.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*CNoUQNlHXjIckwINKYPOZA.png" /></figure><p>This introduction to CSS selectors begins by offering a hands-on lesson covering various selectors, complete with examples. Following this, there will be a guided section dedicated to constructing a neumorphic form similar to the picture above. This part of the tutorial will utilize a range of selectors to further reinforce the concepts covered.</p><h3>Section 1:</h3><h3>Understanding CSS Selectors</h3><p>A selector acts as a marker placed on an element, enabling the application of CSS styling to that element. It’s akin to tagging a suitcase with a unique identifier at the airport or labeling a file for easy retrieval. This identification allows us to navigate to our CSS stylesheet and apply specific rules to the designated elements. With a plethora of CSS selectors available, they are organized into distinct categories for easier understanding and application:</p><p><strong><em>Basic Selectors</em></strong></p><ul><li>Universal Selector: Use * to apply styles across all elements.</li><li>Tag Selectors: Target elements by their tag name, like div or p.</li><li>Class Selectors: Apply styles to elements with a specific class using .classname.</li><li>ID Selectors: Single out elements with a unique ID using #idname.</li><li>Attribute Selectors: Select elements based on the presence or value of an attribute with [attr=value].</li></ul><p><strong><em>Grouping Selectors</em></strong></p><ul><li>Combine different selectors (A, B) to distribute shared styles efficiently.</li></ul><p><em>Combinator Selectors</em></p><ul><li>Define element relationships, targeting descendants (A B), direct children (A &gt; B), adjacent siblings (A + B), or general siblings (A ~ B).</li></ul><p><em>Pseudo-Class Selectors</em></p><ul><li>Adapt styles based on element state (:hover, :active), purpose (:target), language (:lang()), UI state (:checked, :disabled), structural positioning (:first-child, :nth-of-type()), or exclusion (:not()).</li></ul><p><em>Pseudo-Element Selectors</em></p><ul><li>Customize specific parts of elements with ::before, ::after, ::first-line, ::first-letter, and ::selection.</li></ul><p><em>Attribute Selectors</em></p><ul><li>Refine element selection based on attribute presence, exact value match, value containment, value prefix (^=), suffix ($=), or a specific pattern (|=).</li></ul><p><em>Advanced CSS3 Selectors</em></p><ul><li>Elevate targeting precision with structural pseudo-classes like :nth-child(), and employ negation with :not(selector) for selective styling exclusion.</li></ul><p>In the following sections, we’ll explore a few of these selectors through illustrative example snippets to cement your understanding of how these selectors can be effectively utilized in web design.</p><h3>Basic Selectors</h3><p><em>Global Selector: </em><em>* to apply styles across all elements.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*cK2Rf_woGrrn-6IxhjXS-g.png" /><figcaption>Every element has a green font</figcaption></figure><p><em>Tag Selectors: Target elements by their tag name, like </em><em>div or </em><em>p.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*ZZY2febJVTFnw4VYRksiiw.png" /><figcaption>All divs have a font color of blue rule</figcaption></figure><p><em>Class Selectors: Apply styles to elements with a specific class using </em><em>.classname</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wpZd-P_WrBAPTyjOzwYhw.png" /><figcaption>Both hi there and my name is has a class name of div-selector and they each have an orange font color</figcaption></figure><p><em>ID Selectors: Single out elements with a unique ID using </em><em>#idname</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*kbPVvrWh9uNjoiHW3_R1YA.png" /><figcaption>#name has my name and a rule of font-size at 30px with font color red</figcaption></figure><p><em>Attribute Selectors: Select elements based on the presence or value of an attribute with </em><em>[attr=value]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*E-ZFhdgA8SYD4rUB5Ni1OA.png" /><figcaption>button has a black background and 40px font size</figcaption></figure><h3>Basic Selectors Activity</h3><p>In this activity, you will practice using different types of CSS selectors to style HTML elements. Follow the steps below and try to apply the specified styles using the appropriate selectors. Use a code editor or an online platform like CodePen to write your HTML and CSS.</p><p><a href="https://codepen.io/pen/">CodePen - Create a New Pen</a></p><h4>HTML Structure</h4><p>Start by creating the following HTML structure in your editor:</p><pre>&lt;div class=&quot;info&quot;&gt;This is a generic div element.&lt;/div&gt;<br>&lt;div class=&quot;info&quot;&gt;Another generic div element.&lt;/div&gt;<br>&lt;p class=&quot;text-info&quot;&gt;This is a paragraph.&lt;/p&gt;<br>&lt;a href=&quot;#&quot; id=&quot;link&quot;&gt;This is a link&lt;/a&gt;<br>&lt;input type=&quot;button&quot; value=&quot;Click Me&quot; class=&quot;button&quot;&gt;</pre><h4>CSS Tasks</h4><ol><li>Universal Selector: Use the universal selector to set the font-family of all elements to Arial, sans-serif.</li><li>Tag Selector: Use a tag selector to change the color of all &lt;div&gt; elements to navy.</li><li>Class Selector: Use a class selector to make the text of elements with the class .info bold and change their background color to lightgrey.</li><li>ID Selector: Use an ID selector to increase the font size of the element with the ID link to 20px and change its color to green.</li><li>Attribute Selector: Use an attribute selector to style the input element with the type=&quot;button&quot; attribute by changing its background color to orange, and text color to white.</li></ol><p>After completing the tasks, experiment by adding more elements and styles to further explore the capabilities of CSS selectors. This activity is designed to help you understand how different selectors are used to apply specific styles to various elements in a webpage.</p><h3><strong><em>Grouping Selectors</em></strong></h3><p><em>Combine different selectors (</em><em>A, B) to distribute shared styles efficiently.</em></p><blockquote>This is very different from (A B) which does not have a common. -&gt; this targets B and not both A and B</blockquote><p>In the example below, div and button would be A and B but you could also have A, B, C...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*2-VNkArTgvM9HhvnhUpV8w.png" /></figure><h3>Group Selectors Activity</h3><p>In this activity, you’re tasked with optimizing and simplifying the CSS by grouping selectors that share common styles. This exercise aims to reduce redundancy and promote cleaner, more maintainable code. Using the same HTML structure as before, apply the following style rules using group selectors.</p><p>Reuse the HTML structure from the previous activity:</p><pre>&lt;div class=&quot;info&quot;&gt;This is a generic div element.&lt;/div&gt;<br>&lt;div class=&quot;info&quot;&gt;Another generic div element.&lt;/div&gt;<br>&lt;p class=&quot;text-info&quot;&gt;This is a paragraph.&lt;/p&gt;<br>&lt;a href=&quot;#&quot; id=&quot;link&quot;&gt;This is a link&lt;/a&gt;<br>&lt;input type=&quot;button&quot; value=&quot;Click Me&quot; class=&quot;button&quot;&gt;</pre><p><a href="https://codepen.io/pen/">CodePen - Create a New Pen</a></p><h4>CSS Tasks</h4><ol><li>Group Selector for Text Color: Create a group selector that changes the text color of the &lt;div&gt; elements with the class .info, the paragraph &lt;p&gt; with the class .text-info, and the &lt;a&gt; element with the ID link to darkslategray.</li><li>Group Selector for Font Family: Use a group selector to set the font family of the &lt;div&gt;, &lt;p&gt;, and &lt;a&gt; elements to Verdana, sans-serif.</li><li>Unified Hover Effect: Implement a group selector for a hover effect that changes the text color to darkorange for both the &lt;a&gt; element and the input button when hovered over.</li></ol><h3><em>Combinator Selectors</em></h3><p><em>targeting descendants (</em><em>A B)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*8kOaIaAbokyJbFntL7ffnw.png" /></figure><p><em>direct children (</em><em>A &gt; B)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*Y6wcp9TFKcX8QnN4e2eGnw.png" /></figure><p><em>adjacent siblings (</em><em>A + B)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*BAv1n_3GUZl-e-W32WmUuQ.png" /></figure><p>general siblings (A ~ B), all siblings that follow after A</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*PXvrQxbK0MSyrqAh0CcPug.png" /></figure><h3>Combinator Selectors Activity</h3><h4>Objective</h4><p>Use combinator selectors to style a list of articles, applying specific styles to headings, descriptions, and tags based on their relationships within the HTML structure. You have starter HTML code below:</p><pre>&lt;div class=&quot;content&quot;&gt;<br>  &lt;article&gt;<br>    &lt;h2&gt;Article Title 1&lt;/h2&gt;<br>    &lt;p&gt;Description of the first article.&lt;/p&gt;<br>    &lt;ul class=&quot;tags&quot;&gt;<br>      &lt;li&gt;HTML&lt;/li&gt;<br>      &lt;li class=&quot;highlight&quot;&gt;CSS&lt;/li&gt;<br>      &lt;li&gt;JavaScript&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/article&gt;<br>  &lt;article&gt;<br>    &lt;h2&gt;Article Title 2&lt;/h2&gt;<br>    &lt;p&gt;Description of the second article.&lt;/p&gt;<br>    &lt;ul class=&quot;tags&quot;&gt;<br>      &lt;li&gt;Web Design&lt;/li&gt;<br>      &lt;li class=&quot;highlight&quot;&gt;Graphic Design&lt;/li&gt;<br>      &lt;li&gt;UX/UI&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/article&gt;<br>&lt;/div&gt;</pre><p><a href="https://codepen.io/pen/">CodePen - Create a New Pen</a></p><h4>CSS Tasks</h4><ol><li>Descendant Combinator: Change the font color of all list items (&lt;li&gt;) within .tags to dark grey.</li><li>Child Combinator: Increase the font size of descriptions (&lt;p&gt;) that are direct children of &lt;article&gt;.</li><li>Adjacent Sibling Combinator: Style the &lt;ul&gt; that immediately follows a &lt;p&gt; to have a top border.</li><li>General Sibling Combinator: Specifically target the .highlight class within ul that follows any &lt;h2&gt;, making its text bold and color red.</li></ol><h3><strong>Section 1 Conclusion</strong></h3><p>In wrapping up, we won’t be diving into pseudo and advanced CSS3 selectors here, but we highly encourage you to explore these on your own. Getting familiar with them will seriously up your design game, giving you a whole lot more options to get creative with your web projects.</p><h3><strong>Section 2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*tDUQ8FZEBUcaEbNrj9pEPA.gif" /></figure><p>In this section, you’ll have the opportunity to create the neumorphic form above on your own. We’ll provide you with the HTML structure and a list of CSS properties and their values that are essential for the neumorphic look. Your task is to write the CSS selectors and declaration blocks, applying these given properties and values to the appropriate elements to bring the neumorphic design to life. Let’s see how you can apply what you’ve learned to achieve this. Here’s your starting point with the HTML structure for the form:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;<br>  &lt;title&gt;replit&lt;/title&gt;<br>  &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>  &lt;div class=&quot;form&quot;&gt;<br>    &lt;h2&gt; Login&lt;/h2&gt;<br>    &lt;div class=&quot;input&quot;&gt;<br>      &lt;div class=&quot;input-box&quot;&gt;<br>        &lt;label&gt; Username&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;example@gmail.com&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;input-box&quot;&gt;<br>        &lt;label&gt; Password&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;1234&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;input-box&quot;&gt;<br>        &lt;input type=&quot;submit&quot; name=&quot;&quot; value=&quot;Sign In&quot;&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;p class=&quot;forgot-password&quot;&gt; Forget Password? &lt;a href=&quot;#&quot;&gt; Click Here&lt;/a&gt; &lt;/p&gt;<br>  &lt;/div&gt;<br><br><br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>And here are the properties and values you’ll need to incorporate into your CSS. Remember, it’s up to you to determine which elements these styles should apply to:</p><pre><br>  display: block; <br>  margin-top: 20px;<br>  margin-left: auto;<br>  margin-right: auto;<br>  width: calc(100% - 100px); <br>  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.25), -8px -8px 12px 0 rgba(255,255,255,0.3);<br>  color: #131419;<br>  margin-top: 20px;<br>  box-shadow: inset 8px 8px 16px 0 rgba(0,0, 0, 0.25), inset -8px -8px 12px 0 rgba(255,255,255,0.3);<br>  color: #555;<br>  font-size: 18px;<br>  margin-top: 30px; <br>  color: #555;<br>  color: #fff;<br>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&amp;display=swap&#39;);<br>  width: 350px;<br>  padding: 40px 40px 60px;<br>  background: #afd275;<br>  border-radius: 10px;<br>  text-align: center;<br>  box-shadow: 25px 16px 16px 0 rgba(0,0, 0, 0.25), -10px -10px 12px 0 rgba(255,255,255,0.3);<br>  color: #131419;<br>  font-weight: 500;<br>  text-transform: uppercase;<br>  letter-spacing: 4px;<br>  text-align: left;<br>  margin-top: 40px;<br>  margin-top: 20px;<br>  display: block; <br>  color: #131419;<br>  margin-bottom: 5px;<br>  font-size: 18px;<br>  width: 100%;<br>  height: 50px;<br>  background: #afd275;<br>  border: none;<br>  outline: none;<br>  border-radius: 40px;<br>  padding: 5px 15px;<br>  font-size: 18px;<br>  color: #131419;<br>  box-shadow: inset 8px 8px 16px 0 rgba(0,0, 0, 0.25), inset -8px -8px 12px 0 rgba(255,255,255,0.3);<br>  margin: 0;<br>  padding: 0;<br>  box-sizing: border-box;<br>  font-family: &#39;Poppins&#39;, sans-serif;<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  min-height: 100vh;<br>  background: #afd275;<br>  position: relative;</pre><h3><strong>Conclusions:</strong></h3><p>Alright, let’s wrap this up! We’ve gone through the ins and outs of CSS selectors and even tackled creating a neumorphic form. While we didn’t get into pseudo and advanced CSS3 selectors, diving into those on your own is a great next step. They’ll really amp up what you can do with your designs.</p><p>Don’t stop here. The more you mess around with CSS, the cooler stuff you’ll be able to make. And remember, if you ever get stuck, there’s a whole internet out there full of examples and folks who’ve probably faced the same issues. Keep experimenting and learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa9289a81e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>