Adjust the translateX value and element size based on either the parent element's size or the window's dimensions

Is this question specific enough to relate to others' problems?

My issue involves two elements, a child and a parent, with the child element rotating around the parent using CSS animations.

<div class="planet">

<div class="moon"></div>

</div>

The moon's animation is designed so that it initially loads on top of the planet in the same position, but is then pushed out with translateX and rotated:

@keyframes myOrbit {
from { transform: rotate(0deg) translateX(200px) rotate(0deg); }
to   { transform: rotate(360deg) translateX(200px) rotate(-360deg); }
}

Imagine a planet with a moon orbiting around it.

When the user resizes the window, both the planet's height/width and the moon's height/width should resize. Additionally, the distance between the moon and the planet needs to decrease.

I have provided an example here: https://codepen.io/anon/pen/mVvYbR

Is it possible to achieve this effect using just CSS, or would JavaScript be necessary? I am willing to use jQuery if needed, although I prefer a cleaner CSS solution.

Currently, the setup has the planet div containing the moon for the purpose of having multiple children (multiple moons). However, this may lead to numerous animations for different moons with varying translateX values. In such cases, maybe jQuery would be a better solution...

If anything is unclear, please let me know.

Thank you!

Answer №1

If you want to achieve this using only CSS, consider using viewport units for responsive design that adapts to the screen size.

.planet {
    width: 10vw;
    height: 10vw;
      background: url(http://placehold.it/940x940) no-repeat center center;
    background-size: contain;
    z-index: 1;
}

.moon {
    position: absolute;
    background: url(http://placehold.it/140x140) no-repeat center center;
    background-size: contain;
    width: 5vw;
    height: 5vw;
    -webkit-animation: myOrbit 20s linear infinite;
       -moz-animation: myOrbit 20s linear infinite;
         -o-animation: myOrbit 20s linear infinite;
            animation: myOrbit 20s linear infinite;
}

@keyframes myOrbit {
    from { transform: rotate(0deg) translateX(20vw) rotate(0deg); z-index:1}
    to   { transform: rotate(360deg) translateX(20vw) rotate(-360deg); z-index:2}
}

See a demonstration -> here

To ensure optimal display on different devices, you may need to implement media queries for varying screen ratios. Check current support for viewport units -> caniuse.com

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

Adjust the position of elements based on their individual size and current position

I am faced with a challenge regarding an element inside a DIV. Here is the current setup... <div id="parent"> <div id="child"></div> </div> Typically, in order to center the child within the parent while dynamically changing i ...

Experiencing the error message "Uncaught TypeError: Cannot read property 'push' of undefined" unexpectedly popping up at random intervals

Hey there, I've encountered an issue while trying to fetch data from a URL and populate it into an array. The process involves pushing the fetched data into the "data" property of each element in the array, and then repeating this process recursively. ...

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...

Controling attributes during the design process

Experimenting with a basic User Control in Visual Studio 2008: I've created a Panel called Wrapper with various controls inside. Will Visual Studio be able to handle this during the design phase? public partial class TestControl : System.Web.UI.UserC ...

Using JQuery to Give the TinyMCE Editor Focus: A Step-by-Step Guide

My current challenge involves adding text to the TinyMCE editor using SELENIUM. I have successfully added text with the following code snippet: $('iframe').last().contents().find('body').text('401c484b-68e4-4bf2-a13d-2a564acddc04& ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: Code Snippet: const Fingerprint = require(&apo ...

Position a form in the center of a container and showcase an additional div on the right with an indentation

My goal is to center a form within a div and have another div on the right that is slightly indented, but I'm struggling to align the elements properly. How can I achieve this layout using CSS? Additionally, is there a way to center the right-hand d ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

AngularJS ng-submit can be configured to trigger two separate actions

I am currently diving into AngularJS and working on a simple project to create an expense tracker as a beginner task. However, I have encountered some issues with my code. While I have successfully implemented most functions, I am struggling with the upda ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

The state remains constant upon clicking

Below is the code snippet of my component: import React from "react"; import { useState } from "react"; import { Text, SvgContainer, Svg, Flex } from "../lib/styles"; import Modal from "./Modal"; const Credits = () ...

The callback function is unable to access this within the $.post method

Hey there, I'm new to JavaScript/jQuery and I could use some help. I have an object prototype called Page that contains an array and a function for making an AJAX POST request and processing the response. Here's a snippet of the code: function P ...

Is it possible for URLs in CSS Custom Properties to be relative to the CSS file where they are defined?

I have a CSS library with resources like images and fonts that can be accessed from anywhere via CDN. I am trying to create URLs for these resources as Custom CSS Properties, relative to the library. <!-- https://my.server/index.html --> <link rel ...

Action of Submit Button Based on Field Matching Another Form

I currently have a single page that contains two forms, with only one form being displayed at the moment. The concept is that if the user selects a specific state from the drop-down menu and clicks on the submit button, they will be redirected to either a ...

Navigating the world of updating problems with Express.js

Currently, I am working on a MEAN stack project and facing challenges with the routing for updating. Saving operations are functioning correctly. In my Angular controller, I have defined the following scope method in which staff represents the object subm ...

Focus on targeting dynamic IDs such as #event_rules_attributes_0_interval, #event_rules_attributes_1_interval, etc. using CSS3 styling

Styling input tags using their IDs can be very convenient due to the higher precedence weight they hold compared to classes. For instance, I set a default width for input.text elements within a specific container: .details .metadata input.text { width: 2 ...

Undefined elements in an array of objects in Javascript

I've been working on creating an array of objects in JavaScript, but I'm facing an issue when attempting to print the array to the console in Chrome. It keeps returning undefined unless I print the array right after pushing new elements into it. ...

Using Three.js and EffectComposer to create interactive masking with an UnrealBloomPass

Struggling with dynamically masking an UnrealBloomPass using the EffectComposer and encountering unexpected outcomes. Uncertain if missing a crucial concept or exploring the wrong approach. Any insights would be greatly valued. The composer consists of th ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

Update the second mouse click functionality using jQuery

I currently have a jQuery function integrated into my WordPress portal that manages the functionality of the menu and the display of subcategories to ensure proper mobile optimization. This code, which was created by the theme editor, handles these aspects ...