Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out?

I'm trying to center an image, a message, and a password input on my webpage. While it looks good on my screen, in the code snippet below, there seems to be no space below the password line (you may need to scroll around to see anything), so clearly something is amiss...it's supposed to be perfectly centered on the screen.

However, I feel like I'm not efficiently positioning my elements. I also want to ensure that when the user shrinks their window, scroll bars appear and any empty space disappears (similar to Twitter's login page: https://twitter.com/login). Unfortunately, in my current code, shrinking the window still leaves empty space which I believe is not ideal for UI.

In essence, if anyone has tips on how to effectively position text and images, as well as utilize CSS to handle window resizing gracefully, I would greatly appreciate the guidance :) Any help is welcome and thank you in advance!

.pretty {
  text-align: center;
  color: #00008b;
  font-family: Lucida Console;
  position: absolute;
  top: 115%;
  left: 39%;
}

.pwd {
  text-align: center;
  position: absolute;
  top: 155%;
  left: 38.5%;
}

.chatbubble {
  height: 14%;
  width: 6%;
  position: absolute;
  top: 102%;
  left: 48.5%;
}

body {
  background-color: #fff0f5;
}

#wrapper {
  margin-left: auto;
  margin-right: auto;
  width: 960px;
}

.contain {
  position: relative;
  height: 200px;
}

html {
  height: 100%;
}
<!DOCTYPE html>
<html>
<div id="wrapper">

  <head>
    <title> Log In </title>

    <link href="loginstyle.css" type="text/css" rel="stylesheet">

    <script language="JavaScript">
      function showPass(form, e) {
        e.preventDefault();

        var pass = form.pwd.value;
        var pass1 = "webdesign"

        if (pass == pass1) {
          window.location.href = 'https://www.google.com'
        } else {
          window.location.href = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
        }
      }
    </script>

  </head>

  <body>
    <div class="contain">
      <img class="chatbubble" src="chatbubble.png" alt="Chat Bubble" />
      <p class="pretty center">Welcome to a <br/> digital photobook. <br/> Please enter the password to continue: <br/> </p>

      <form class="pwd center" onsubmit="showPass(this, event)">
        Password: <input type="password" name="pwd" />
        <input type="submit" value="Log In" />
      </form>
    </div>
  </body>
</div>

</html>

Answer №1

It is important to note that the wrapper should be positioned inside the body tag, not around the body and head tags:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
    <!-- Content, including wrappers, go here -->
</body>
</html>

Avoid using absolute positioning for responsive web design unless absolutely necessary. There are various ways to center content both horizontally and vertically, with resources available on Stack Overflow. One modern approach is utilizing flexbox.

Instead of setting a fixed width, consider using max-width for your wrapper to prevent scrolling on smaller devices.

An effective strategy for Responsive Web Design (RWD) involves starting with minimal CSS styles geared towards mobile views. Most elements will naturally adjust, but ensure images are styled responsively. As you scale up to larger screens, introduce media queries to reposition elements and adjust font sizes accordingl. Embracing a "mobile first" strategy can also aid in this process.

html {
  height: 100%;
}

body {
  min-height: 100%;
  background-color: #fff;
  margin: 0;
  padding: 0;
}

#wrapper {
  margin: 0 auto;
  padding: 1rem;
  max-width: 960px;
  background-color: #fff0f5;
}

/* login section */

.login-section {
  min-height: 100vh;
  display: flex;
  flex-flow: column wrap;
  justify-content: center;
  align-items: center;
  text-align: center;
}

/* typography */

.pretty {
  color: #00008b;
  font-family: Lucida Console;
}
<!DOCTYPE html>
<html>
<head>
  <title> Log In </title>
  <link href="loginstyle.css" type="text/css" rel="stylesheet">
  <script language="JavaScript">
    function showPass(form, e) {
      e.preventDefault();
      var pass = form.pwd.value;
      var pass1 = "webdesign"
      if (pass == pass1) {
        window.location.href = 'https://www.google.com'
      } else {
        window.location.href = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
      }
    }
  </script>
</head>

<body>
  <div id="wrapper">
  
    <main>
      <section class="login-section">
        <img class="chatbubble" src="https://via.placeholder.com/150" alt="Chat Bubble" />
        <p class="pretty">Welcome to a digital photobook.<br>Please enter the password to continue:</p>
        <form class="pwd" onsubmit="showPass(this, event)">
          Password: <input type="password" name="pwd" />
          <input type="submit" value="Log In" />
        </form>
      </section>
    </main>
    
  </div>
</body>
</html>

Answer №2

Avoid using manual percentage positioning, such as left: 155%. For centering elements, utilize absolute positioning on a wrapper container and then align the content inside with text-align: center. To center containers or images, apply the display: inline-block property so they flow to the center.

Below is an updated version of your CSS code, which you can also view in the snippet:

.contain {
   position: absolute;
   top: 50%;
   left: 50%;
   text-align: center;
   -webkit-transform: translate(-50%, -50%);
   -moz-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}

.pretty {
  text-align: center;
  color: #00008b;
  font-family: Lucida Console;
}

.pwd {
  text-align: center;
}

.chatbubble {
    display: inline-block;
}

body {
  background-color: #fff0f5;
}

html {
  height: 100%;
}
<!DOCTYPE html>
<html>
<div id="wrapper">

  <head>
    <title> Log In </title>

    <link href="loginstyle.css" type="text/css" rel="stylesheet">

    <script language="JavaScript">
      function showPass(form, e) {
        e.preventDefault();

        var pass = form.pwd.value;
        var pass1 = "webdesign"

        if (pass == pass1) {
          window.location.href = 'https://www.google.com'
        } else {
          window.location.href = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
        }
      }
    </script>

  </head>

  <body>
    <div class=“contain”>
      <img class="chatbubble" src="chatbubble.png" alt="Chat Bubble" />
      <p class="pretty center">Welcome to a <br/> digital photobook. <br/> Please enter the password to continue: <br/> </p>

      <form class="pwd center" onsubmit="showPass(this, event)">
        Password: <input type="password" name="pwd" />
        <input type="submit" value="Log In" />
      </form>
    </div>
  </body>
</div>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing specific values from a JSON object in JavaScript

I'm fairly new to JSON and have a JSON String that I'd like to access and print to a DIV. I've managed to get it working using the following code snippet: document.getElementById("product_content").innerHTML=javascript_array[5].name; The s ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...

Obtaining a unique diamond pattern overlay on my Google Map

Currently, I am integrating Vue.js with vue-google-maps, and I have noticed a diamond-shaped watermark appearing on the map. After reaching out to Google support, they mentioned that this issue is specific to my tool, indicating it might be related to eith ...

Transform a value nested at any depth into an object key using Ramda or plain JavaScript

I have encountered a unique scenario while using a specific library. Instead of returning an array, this library returns nested objects with the final leaf node containing the value. For instance: red.walk.fast.true is returned as {red: {walk: {fast: &apo ...

Having issues with Django not recognizing multiple identical GET parameter names

A Django form is being used for filtering data via a GET form: from reservations.models import Reservation, ServiceType from django import forms PAYMENT_OPTIONS = ( ('CASH', 'Cash'), ('ROOM', 'Charge to room&apo ...

What is the best way to create a stylish outward curve effect for an active sidebar item using just CSS

After spending a week learning frontend designs, I attempted to replicate a design from Dribble. However, I've been struggling with recreating the active style on the sidebar due to the outward curve. If anyone could provide guidance on achieving thi ...

Ways to adjust image placement and size post-rotation with CSS/JS to ensure it stays within the containing div and avoids being cut off

Check out this jsfiddle I've been experimenting with. The jsfiddle is designed to rotate an image by 90 degrees in either clockwise or anti-clockwise direction upon button click. However, the rotated image currently appears outside of its parent div. ...

Trigger a click event on a third-party webpage that is embedded within an Angular application

In the process of developing my angular application, I found a need to incorporate a graph visualization tool. To achieve this, I utilized the HTML <embed> tag and successfully integrated the graph into my application. Now, my objective is to enable ...

Guide to incorporating tesseract OCR into a Cordova/Phonegap application

My attempts to use Tesseract OCR with my app have been unsuccessful despite following the instructions provided here. After inspecting the code using Google Chrome Dev console through the WebView, I encountered an error: Uncaught SyntaxError: Unexpected ...

Tips for obtaining the correct Javascript output for the number pyramid

I'm currently in the process of creating a half pyramid of numbers, but I'm facing an issue with getting the output to show the total for each line while maintaining everything except the * sign between the numbers. If anyone is able to offer som ...

Unify your navigation with Bootstrap 5 - harnessing the power of two navs

I am struggling with a code that has three identical blocks, each with at least two navigation items and one tab content. The issue I am facing is that I can't figure out how to deselect the active item in the other lists when one is clicked on. I c ...

Issues with TypeScript arise when transferring arguments between functions

Encountering a TypeScript error due to this pattern: Error message: 'Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]' function foo(value: string | number) { return bar([va ...

A comprehensive guide on implementing form array validations in Angular 8

I am currently using the formArray feature to dynamically display data in a table, which is working perfectly. However, I am facing difficulty in applying the required field validation for this table. My goal is to validate the table so that no null entry ...

Learn how to use JavaScript to parse binary files

Is there a way to interpret this binary data below? Binary2 { sub_type: 0, buffer: Buffer(16) [ 12, 15, 64, 88, 174, 93, 16, 250, 162, 5, 122, 223, 16, 98, 207, 68 ], position: 16 } I've attempted different methods like using ...

jQuery Triggered Download Resulting in 'Error: Connection Issue'

I need to trigger a download using a JQuery AJAX request once it's finished. EXAMPLE CODE: $('.getPDF').click(function(){ var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf'; $.ajax({ url: '/formu ...

What is the process for assigning a PHP function's return value to a JavaScript variable?

Is there a way to retrieve a value from a PHP function and assign it to a JavaScript variable? As shown in the following example: PHP: // Destination folder for downloaded files $date = date('m.d.y'); mkdir("uploads/" . $date, 0777, true); $ ...

Making changes to a variable or option through the props in a different file

In the index.js file, I have implemented getStaticProps() to fetch data from an exported function. This function requires 2 parameters, one for the type of listing and the quantity. export async function getStaticProps() { const type = 0 const data = a ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

Adjust the wait time for sliding on the jQuery rcarousel

I am currently utilizing rcarousel for my website and I would like to adjust the duration of time that each slide is displayed. At the moment, each slide stays up for just a few seconds, but I want to extend this so that each slide remains on screen for at ...

"Using Selenium in Python to navigate Google's search results and view the

Hello, I am new to using selenium and I have a specific task in mind. I would like to scrape the address search results from Google that are displayed on the sidebar column. I have successfully managed to use selenium to conduct searches on Google and land ...