Merge floating and absolute positioning techniques

Creating a calendar exhibiting all events in one div requires precise positioning based on the values of top and height. Let me demonstrate this concept.

In the image below, both 6am events are aligned vertically. This alignment issue can be resolved by using float: left(jsfiddle).

If there are no conflicts with the vertical alignment (where the height and top do not overlap), I can mimic this behavior with absolute position(jsfiddle), but not through float.

The Dilemma

The challenge arises while attempting to position the events at 9am and 9:40am precisely as depicted in the image mentioned earlier. Consider the following properties:

  • 9:00 height: 50px, top: 200px
  • 9:40 height: 50px, top: 230px
  • Bottom of 9:00 event: 200px + 50px = 250px
  • Top of 9:30 event: 230px
  • Hence, they share 20px (250px - 230px) vertically.

Therefore, my attempted solution involved the following code snippet:

<div class="container">
    <div class="event" style="height: 50px; top: 200px; float:left;">9 AM</div>
    <div class="event" style="height: 50px; top: 230px; float:left;">9:40 AM</div>
</div>

...but the float property does not function in elements with absolute position.

Summary

The intention is to utilize the top value as a reference point for vertically placing the event within the calendar corresponding to its respective hour. For instance,

  • 6am -> top: 100px
  • 7am -> top: 150px
  • 8pm -> top: 200px

Approaches

I endeavored to tackle this challenge solely with CSS, yet I am open to integrating JavaScript if necessary. Unfortunately, I cannot illustrate my attempts with JavaScript as I have not achieved substantial results even with CSS manipulation. While I initially opted for the top property assuming it would facilitate easy positioning adjustments, I am willing to explore alternative methods if required. Thank you for your assistance in advance.

Answer №1

By utilizing relative positioning, the issue you are experiencing is almost resolved. However, there are still gaps between events:

Fiddle #1

To completely address this problem, absolute positioning must be used with JavaScript to determine the top and left coordinates:

var events= [].slice.call(document.querySelectorAll('.container div')),
                //array of event elements. See http://davidwalsh.name/nodelist-array
    count= [],  //running total of events during an hour. used to calculate left offset.
    i,          //loop through the events
    time,       //event time as array, such as ['6','AM']
    hour,       //event hour (1 - 24)
    minute,     //event minute (0 - 59)
    offset;     //top offset based on hour and minute

events.sort(function(a,b) {
  return a.textContent < b.textContent ? -1 : 1;
});

for(i = 0 ; i < events.length ; i++) {
  time= events[i].textContent.split(' ');
  hour= time[0].split(':')[0] * 1;
  if(time[1]==='PM' && hour !== 12) {
    hour+= 12;
  }
  minute= time[0].split(':')[1] || 0;
  offset= hour+minute/60;
  count[hour]= (count[hour] || 0)+1;
  events[i].style.top= (offset-6)*50 + 'px';
  events[i].style.left= count[hour]*100-100 + 'px';
}

Fiddle #2

Please note that some adjustments are required in the code to prevent events from overlapping, as demonstrated in the Fiddle for 12:00 PM.

Answer №2

To improve the layout of your divs, consider incorporating positioning. By adding position:relative to your classes, you can utilize top:xxpx for adjusting the vertical position. Keep in mind that there may be various edge cases that could pose challenges for a purely CSS solution, but this suggestion might provide some assistance.

Check out this demo on jsFiddle: http://jsfiddle.net/markm/qvevedva/

Answer №3

Have you considered using margin-top instead of top? It may give you the desired outcome:

You could also try wrapping each hour in a container div and placing the event divs inside:

<div class="container">
   <div class="event" style="height: 50px;">6AM</div>
   <div class="event" style=" height: 50px;">6AM</div>
</div>
<div class="container">
   <div class="event" style="height: 50px;">9 AM</div>
   <div class="event" style="height: 50px; margin-top: 25px;">9:30 AM</div>
   <div class="event" style="height: 50px; margin-top: 33px;">9:40 AM</div>
</div>

Check out this sample code on JSFiddle for more details.

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

In a scenario where multiple fields need to be incremented, one can accomplish this by incrementing one field every time while also increasing the other field only if it exceeds a

When trying to decrement class_number, everything works fine. However, the issue lies with number_of_classes not being decremented due to the usage of the $gt operator. posts.update({ 'title':doc.title, 'author':doc.author, 'class ...

Mobile site experiencing owl.carousel responsiveness issues after refreshing the page

I am currently working on a website located at . On the homepage, right after the slider, there is a carousel of three info boxes. However, in mobile view (developer mode), after a hard refresh or viewing the link on an actual mobile device, it displays a ...

Challenges with resizing in Bootstrap

I need assistance with my login form that is appearing in a Bootstrap modal. The modal I am using is the standard size, not the larger one. In the form, there are 2 input fields and a login button on the left side, while the right side should contain other ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

What are the steps to designing a unique JSON data format?

When working with a JSON data structure containing 100 objects, the output will resemble the following: [{ "Value": "Sens1_001", "Parent": Null, "Child": { "Value": "Sens2_068", "Parent":"Sens1_001", "Child" : { ...

Calculate the total sum of values in a MySQL column and then group the results

I'm currently working on a quiz website and looking to create a leaderboard. The user scores are stored in a database table named 'user_record' with the following structure: 'user_id' - varchar(254) -holds the user id for a score ...

The Navbar in Bootstrap 3 remains expanded and does not collapse

It seems like there's a simple solution I'm overlooking. When I resize my screen, the navbar collapse toggle stops working. I've searched various forums but couldn't find a fix that works for me. Could someone lend a hand in identifyin ...

Animate hovering over a specific element within a group of similar elements using jQuery

Hi there! I recently started exploring Js and jQuery, and I was able to create a cool width change animation on a div when hovering over another. However, I ran into an issue when trying to implement this with multiple sets of similar divs. Whenever I hove ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

Encountered an issue accessing property 'Component' which is undefined during the webpack build of a React component plugin

I have developed a wrapper for my leaflet plugin called leaflet-arrowheads using react-leaflet. This component is designed to be installed as an npm package, imported, and used easily. The structure of the component is quite simple: import React from &apo ...

Is it possible to invoke a computed property within the props of a child component in Vue.js?

In the context of my child and parent components, I have a boolean prop in the child component with a default value of false. When calling the child component within the parent component and setting it based on a computed function that returns a boolean va ...

Getting information from a JSON file with several variables: A guide for using node.js, express, and jQuery

In order to minimize the number of Ajax calls, I am attempting to send three variables in a single Ajax response. However, I am facing difficulties when trying to process the data on the client side. Let me elaborate on my issue and if sending multiple var ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

Every time the Select box choice is changed, Jade Pug will undergo a new iteration

Recently, I began using a Pug/Jade template to go through an object of events sent from an express app. Everything is working smoothly, but now I've added a select box with a dropdown populated by venues in the event object. I'm facing a seemingl ...

Should I use several if get statements on one page, or spread them out across multiple pages in PHP structure?

After working with PHP for a few years, one of my ongoing dilemmas is how to best structure my pages. Should I follow the current approach: if(getValue('action') == "jobsFilter" && getValue('jobType') == "open") ...

using jQuery to eliminate an HTML element based on its attribute

How can I remove an element with the attribute cursor = "pointer"? I want to achieve this using JavaScript in HTML. Specifically, I am looking to remove the following item: <g cursor="pointer"></g>. It's unclear to me why this element has ...

Unusual Display of Mantine Radio Button

I am currently using Mantine v7.0.0 in combination with Next.js v13.5.2 and Tailwind v3.3.3. In my setup, when I create <Radio /> elements, the svg of the element is appearing separately from the radio button instead of replacing it. This issue can b ...

Why is the promise not returning an integer value, but instead returning undefined?

My validation process includes checking the integrity of the down streaming data to the server and verifying its existence in the database. The code snippet from model.js: const mongoose = require('mongoose'); const User = new mongoose.Schema({ ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...