What is the trick to positioning the dice above the green circle and below the line, as shown in the image?

I'm struggling to position the large green circle and the dice image on top of each other as well as below each other. How can I achieve the desired layout shown in this image? Here's what I have managed to do so far https://i.sstatic.net/ryIPl.png

I attempted to use the position property, but setting left: 0px only centered the green circle.

Below is my code:

'use strict';

const dice = document.getElementById('dice');

const adviceContainer = document.querySelector('#box');

const renderAdvice = function (data) {
  const html = `
    <h1 class="heading">ADVICE <span class='hash' id="hash">#${data.slip.id}</span></h1>
      <p class="advice" id="advice">'${data.slip.advice}' </p>
      <img src="/images/pattern-divider-mobile.svg" alt="divider" class="divider">
    `;
  adviceContainer.innerHTML = html;
};

async function adviceGenerator() {
  const res = await fetch('https://api.adviceslip.com/advice');

  const data = await res.json();
  renderAdvice(data);
}

dice.addEventListener('click', adviceGenerator);

adviceGenerator();
@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;800&display=swap');

* {
    box-sizing: border-box;
}

body {
    font-family: Monrope, 'Arial', 'sans-serif';
    background-color: hsl(220, 22%, 16%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
/* More CSS code continues... */
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">
  <title>Frontend Mentor | Advice generator app</title>
</head>
<body>
  <section id="container">
    <section class="box" id="box">
      <!-- <h1 class="heading">ADVICE <span class='hash' id="hash">#</span></h1>
      <p class="advice" id="advice">'Lorem ipsum dolor sit amet consectetur adipisicing elit.!' </p> -->
    </section>
    <span class="green"></span>
    <img src="/images/icon-dice.svg" alt="dice" class="dice" id="dice">
  </section>
  <div class="attribution">
    Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>.
    Coded by <a href="https://www.linkedin.com/in/nelson-uprety-951a2b156/">Nelson Uprety</a>.
  </div>
  <script src="script.js"></script>
</body>
</html>

Answer №1

Instead of using separate elements, you can create a single div with a green background color and a centered background image that is 50% of the size. This approach eliminates the need to align multiple elements within the same container.

Check out this straightforward example:

div {
  background-color: palegreen;
  background-image: url(https://picsum.photos/id/237/300/300);
  background-size: 50% 50%;
  background-position: center center;
  background-repeat: no-repeat;
  border-radius: 50%;
  width: 30vmin;
  aspect-ratio: 1 / 1;
}
<div></div>

Answer №2

You may want to consider reorganizing your HTML structure and simplifying your JavaScript code for better efficiency.

'use strict';

const dice = document.getElementById('dice');

const adviceContainer = document.querySelector('#box');

const displayAdvice = function (data) {
  document.querySelector('#hash').innerText = `#${data.slip.id}`;
  document.querySelector('#advice').innerText = data.slip.advice;
};

async function generateAdvice() {
  const res = await fetch('https://api.adviceslip.com/advice');

  const data = await res.json();
  displayAdvice(data);
}

dice.addEventListener('click', generateAdvice);

generateAdvice();
@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;800&display=swap');

* {
  box-sizing: border-box;
}

body {
  font-family: Monrope, 'Arial', 'sans-serif';
  background-color: hsl(220, 22%, 16%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

#container {
  margin: 100px auto;
  background-color: hsl(218, 20%, 24%);
  border-radius: 10px;
}

.box {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  max-width: 350px;
  min-height: 150px;
  justify-content: center;
}

.heading {
  flex-basis: 100%;
  color: hsl(150, 100%, 66%);
  letter-spacing: 3px;
  text-align: center;
  padding-top: 3em;
  font-size: 0.7em;
  font-weight: 300;
}

.advice {
  flex-basis: 100%;
  color: hsl(203, 33%, 86%);
  font-size: 1.75em;
  font-weight: 800;
  padding: 0.5em;
  text-align: center;
}

.divider {
  flex-basis: 100%;
  display: block;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

.green {
  height: 70px;
  width: 70px;
  border-radius: 50%;
  background-color: hsl(150, 100%, 66%);
  display: inline-block;
  position: relative;
  top: 25px;
}

.dice {
  position: relative;
  height: 30px;
  width: 30px;
  top: 25px;
  left: 5px;
  cursor: pointer;
}

.attribution {
  font-size: 11px;
  text-align: center;
}

.attribution a {
  color: hsl(228, 45%, 44%);
}

@media (min-width: 768px) {
  .box {
    max-width: 450px;
  }

  .green {
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background-color: hsl(150, 100%, 66%);
    display: inline-block;
    position: relative;
    top: 25px;
  }

  .dice {
    position: relative;
    height: 30px;
    width: 30px;
    margin-left: 80px;
    top: 25px;
    left: 39px;
    cursor: pointer;
  }
}

/* https://api.adviceslip.com/ */
/*
Colors
Primary
Light Cyan: hsl(193, 38%, 86%)
Neon Green: hsl(150, 100%, 66%)
Neutral
Grayish Blue: hsl(217, 19%, 38%)
Dark Grayish Blue: hsl(217, 19%, 24%)
Typography
Body Copy
Font size (quote): 28px
Font
Family: Manrope
Weights: 800
*/
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- displays site properly based on user's device -->
    <link
      rel="icon"
      type="image/png"
      sizes="32x32"
      href="./images/favicon-32x32.png"
    />
    <link rel="stylesheet" href="style.css" />

    <title>Frontend Mentor | Advice generator app</title>
  </head>
  <body>
    <section id="container">
      <section class="box" id="box">
        <h1 class="heading">
          ADVICE <span class="hash" id="hash"></span>
        </h1>
        <p class="advice" id="advice"></p>
        <img
          src="/images/pattern-divider-mobile.svg"
          alt="divider"
          class="divider"
        />
        <span class="green"
          ><img src="/images/icon-dice.svg" alt="dice" class="dice" id="dice"
        /></span>
      </section>
    </section>
    <div class="attribution">
      Challenge by
      <a href="https://www.frontendmentor.io?ref=challenge" target="_blank"
        >Frontend Mentor</a
      >. Coded by
      <a href="https://www.linkedin.com/in/nelson-uprety-951a2b156/"
        >Nelson Uprety</a
      >.
    </div>

    <script src="script.js"></script>
  </body>
</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

The MDB Bootstrap collapse fails to display on the initial click

Every time I click on the button, there seems to be a delay in showing the collapse feature. It's strange because on subsequent clicks it works fine ...

Is there a way to determine the length of a variable containing a mixture of characters in HTML and PHP?

Let's say someone wants their username to be GreenApples-72. How can you determine the number of letters, numbers, and symbols in the username and add them together? if((($_POST['username'])<'2')) // Checking if the length of t ...

Guide on accessing and setting values in GridView Cell using JavaScript

Within my layout, I have two labels named FixedTotal and TotalPercent, as well as a single row GridView with columns labeled ReferenceID, Percentage, and Amount. ReferenceID Percentage Amount -------------- ------------- --- ...

Error in identifying child element using class name

I need help accessing the element with the class "hs-input" within this structure: <div class = "hbspt-form".......> <form ....class="hs-form stacked"> <div class = "hs_firstname field hs-form-field"...> <div class = ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

Page Content Fails to Load Without Reloading

I am currently working on a simple project using React with TypeScript, and I have run into an issue where the page content does not refresh as expected without having to reload the page. I am unsure of the underlying cause of this behavior. I have include ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

Photo browser with RTL support and customized previous/next buttons using Framework7

Having an issue with the functionality of the "photo-browser-prev,photo-browser-next" button. It seems to be malfunctioning. Can you please take a look and assist? The photo browser is showing 2 out of 3 images, but the previous button is disabled. Howev ...

Date Boxes in a Tangled Web

Looking to showcase multiple dates on a screen, I'm encountering an issue where clicking on a date button opens a datepicker. If the user clicks out of the box, the datepicker closes properly. However, when another datepicker button is clicked, instea ...

Graphic aligned with textual content

Within my table cell resides text and an accompanying image icon. However, the presence of the image causes the text to shift downwards, not aligning in the center as desired: I am now seeking a solution that will allow the text to be centered within the ...

Tips for handling an InvalidSelectorException in Selenium when logging into a website

I've been working on automating website logins using Selenium and here is the code I have written: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://abcde.com") assert "xxx" in driver.title user = driver.find_element_by ...

Unable to install local dependency using npm

After successfully using npm install react-financial-charts, I decided to include the package locally for specific reasons. I checked out the master branch of react-financial-charts from Github, resulting in two folders: C:\Users\user\projec ...

Shared Vue configuration settings carrying over to Jest spec files

For my unit testing of components using VueJS and Jest, I'm incorporating the Bootstrap Vue library for styling. To address console warnings regarding unknown plugins, I've set up a configuration file: import { createLocalVue } from '@vue/t ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

Get your hands on large files with ease by utilizing jQuery or exploring alternative methods

Within my User Interface, there exists an Advanced Search section where the user can select from 7 different options as depicted in the diagram. Based on these selections, a web service is triggered. This web service returns search results in JSON format, ...

Unnecessary list elements generated by dazzling navbarPage

While developing an app with shiny using navbarPage, I noticed that there are some unwanted li tags in the HTML that are not defined in my code. Could this be a known bug? How can I go about fixing it? <nav class="navbar navbar-default navbar-stati ...

Changing focus to 'DIV' element without JQuery using Javascript and Angular's ng-click event

Instructions for using an Angular directive to set focus on a "DIV" element when clicked <a href="#" class="skipToContent" ng-click="showContent()" title="skip-to-main-content">Skip To Main Content</a> <div class="getFocus" role="button" ...

Styling with CSS using only numerical values

My website features a section that states "Weekdays 10:00 ~ 18:00 /*linebreak/ Saturdays 10:00 ~ 13:30" I am looking to format only the numerical values in the font "Courier New," specifically the "10:00 ~ 18:00" and "10:00 ~ 13:30" sections. The remainin ...

Navigating through an array containing references to object IDs with Mongoose

In my meanjs project, I am receiving user input on the server with a specific request body structure: { transaction: { heading: '', items: [Object] }, something: {}, somethingAgain: {} } The format of the items a ...

Utilize a line break within a MySQL UPDATE statement

After using JSON.stringify, my stringified variable looks like this: {"ops":[{"insert":"drfsdfgg sdfg sdg \ns\ndfg\ndf\nsg\nsdfg\n"}]} However, when I perform an UPDATE, the data in the MySQL database appears as follows: ...