What is the best way to center <div> elements in CSS to give them a target-like appearance and ensure they are aligned perfectly?

I have been attempting to craft a target using div elements, but I am struggling with aligning them in a way that ensures they are all centered and the smallest div element is visible on top. My HTML file only consists of div elements as I am making all modifications in the CSS file. The desired outcome should resemble a target like this, albeit with different colors.Target

/* box_model.css */
div {
    height: 50px;
    width: 50px;
    background-color: red;
    border-radius: 50px;
    display: inline-block;
    position:absolute;
}
div:nth-of-type(2) {
    height: 100px;
    width: 100px;
    background-color: orange;
    border-radius: 50px;
    display: inline-block;
    position: relative;
}
div:nth-of-type(3) {
    height: 150px;
    width: 150px;
    background-color: yellow;
    border-radius: 80px;
    display:inline-block;
    position: relative;
}

div:nth-of-type(4) {
    height: 250px;
    width: 250px;
    background-color: green;
    border-radius: 150px;
    display: inline-block;
    position: relative;
}
<div></div>
<div></div>
<div></div>
<div></div>

Answer №1

To start, the parent container (in this scenario, body) was given a display of flex. Following that, all children were positioned absolutely to allow them to stack on top of each other using z-index. Lastly, a vertical transform was included to adjust for their individual heights and ensure the elements were accurately centered on the screen.

Note: I consolidated the border-radius declarations into a single line in order to simplify things for you.

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

body>div {
  position: absolute;
  transform: translateY(-50%);
  top: 50%;
  border-radius: 50%;
}

div {
  height: 50px;
  width: 50px;
  background-color: red;
  display: inline-block;
}

div:nth-of-type(1) {
  z-index: 4;
}

div:nth-of-type(2) {
  height: 100px;
  width: 100px;
  background-color: orange;
  z-index: 3;
}

div:nth-of-type(3) {
  height: 150px;
  width: 150px;
  background-color: yellow;
  z-index: 2;
}

div:nth-of-type(4) {
  height: 200px;
  width: 200px;
  background-color: green;
  z-index: 1;
}
<div></div>
<div></div>
<div></div>
<div></div>

Result:

https://i.sstatic.net/zd1V9.png

jsFiddle

Answer №2

Here is the CSS code that can help you achieve your desired layout:

.box {
   height: 50px;
   width: 50px;
   background-color: blue;
   border-radius: 10px;
}
.square {
  height: 100px;
  width: 100px;
  background-color: green;
  border-radius: 20px;
}
.rectangle {
  height: 150px;
  width: 200px;
  background-color: purple;
  border-radius: 30px;
}

.circle {
  height: 200px;
  width: 200px;
  background-color: pink;
  border-radius: 50%;
}

And here is the corresponding HTML code:

<div class="circle">
  <div class="rectangle"></div>
  <div class="square"></div>
  <div class="box"></div> 
</div>

Answer №3

#a1{
    display:flex;
    height: 250px;
    width: 250px;
    background-color: green;
    border-radius: 125px;
    z-index:5;
   justify-content:center;
   align-items:center;
}
#a2{
    display:flex;
    height: 200px;
    width: 200px;
    background-color: yellow;
    border-radius: 100px;
    z-index:10;
   justify-content:center;
   align-items:center;
}

#a3{
    display:flex;
    height: 150px;
    width: 150px;
    background-color: orange;
    border-radius: 75px;
    z-index:15;
   justify-content:center;
   align-items:center;
}

#a4{
    display:flex;
    height: 100px;
    width: 100px;
    background-color: red;
    border-radius: 50px;
    z-index:20;
   justify-content:center;
   align-items:center;
}
   
   
implement flexbox with z-index
<div id='a1'>
<div id='a2'>
<div id='a3'>
<div id='a4'></div>
</div>
</div>
</div>

Answer №4

Here are a few strategies you may consider using in this scenario.

To begin with, utilizing absolute positioning allows you to position an object relative to its parent's layout.

It is important to note that absolute positioned elements are placed based on the subsequent parent that has absolute or relative positioning. Therefore, if the immediate parent has position: static, it will be disregarded for the purpose of absolute positioning. This explains why, in my example, I have assigned the container div a position: relative - to ensure the application of absolute positioning.

Secondly, the calc() function enables derived calculations - in this instance, for precise centering, we compute the left and right properties as

50% of the parent's width, minus 1/2 * the desired width of the element
.

Thirdly, the z-index property grants us authority over which element takes precedence visually.

I have promptly adjusted your work, and here is the result.

/* box_model.css */

.container {
    position: relative;
    height: 250px;
    width: 250px; 
}

.container>.target {
    position:absolute;
}
.target:nth-of-type(1) {
    height: 50px;
    width: 50px;
    background-color: red;
    border-radius: 50px;
    z-index: 4; 
    left: calc(50% - 25px); 
    top: calc(50% - 25px); 
}

.target:nth-of-type(2) {
    height: 100px;
    width: 100px;
    background-color: orange;
    border-radius: 50px;
    z-index: 3; 
    left: calc(50% - 50px); 
    top: calc(50% - 50px); 


}
.target:nth-of-type(3) {
    height: 150px;
    width: 150px;
    background-color: yellow;
    border-radius: 80px;
    z-index:2; 
    left: calc(50% - 75px); 
    top: calc(50% - 75px); 
}

.target:nth-of-type(4) {
    height: 250px;
    width: 250px;
    background-color: green;
    border-radius: 150px;
    z-index:1; 
    left: calc(50% - 125px); 
    top: calc(50% - 125px); 

}
<div class = "container"> 
   <div class ="target"></div>
   <div class ="target"></div>
   <div class ="target"></div>
   <div class ="target"></div>
</div> 

It is advisable to refrain from manually assigning z-index values, as your application expands, unintended overlapping issues might arise.

Alternatively, you can regulate the stacking order of elements simply by their document position - such as making the largest circle the first element, rather than the last.

Answer №5

I trust this will be of assistance

.container {
  width: 500px;
  height: 500px;
  border: 1px solid;
  position: relative;
  margin: 20px;
}

.container div:nth-child(1) {
  height: 300px;
  width: 300px;
  background-color: red;
  border-radius: 150px;
  position: absolute;
  top:calc(50% - 150px);
  left: calc(50% - 150px);
}
.container div:nth-child(2) {
  height: 200px;
  width: 200px;
  background-color: white;
  border-radius: 100px;
  position: absolute;
  top:calc(50% - 100px);
  left: calc(50% - 100px);
}
.container div:nth-child(3) {
  height: 100px;
  width: 100px;
  background-color: red;
  border-radius: 100px;
  position: absolute;
  top:calc(50% - 50px);
  left: calc(50% - 50px);
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>

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

Sending FormData from React.js to an Express.js backend results in loss of data

I encountered a problem while developing a book library management CRUD system using React v18. The issue arises when attempting to add data to my MongoDB Atlas database. Whenever I pass the formData to axios.post through Redux, the req.body on the backend ...

The dropdown menu fails to expand when hovered over

<li className={styles.link + " " + styles.hideOnMobile}> <div className={styles.dropdownMenu}> <button className={styles.dropbtn}>Product</button> ...

What is the best way to retrieve a value from an INPUT field and dynamically assign it to a jQuery variable?

Hey everyone! I've got a POST form with a field like this: <input type="text" name="username" /> Using jQuery, I have declared a variable called var username = <---insert code here--->; Here's the question: How can I dynamically as ...

Having trouble with document.getElementById.innerHTML not displaying the correct content?

document.getElementById works in getting the element, but for some reason, the content disappears as soon as it is written in it. There are no errors on the console to indicate what's causing this behavior. I have been unable to identify the reason b ...

Design layout in Angular Material that wraps the content within it

Is there a way to achieve this specific layout with the "plus" icon positioned below the card layout? https://i.sstatic.net/W5ZRM.png I have attempted the code below: <section layout="column" style="background-color: black;"> <md-c ...

The right alignment for ul and li styles is recommended for a cleaner appearance

Here is the fiddle provided below: http://jsfiddle.net/Fx9rA/ <div id="wrap"> <ul id="accordion"> <li> <h2 id="first">CMT</h2> <div class="content"> ...

Despite calling Bootstrap Switch JS, no action is being executed

Struggling with integrating Bootstrap Switch into my project that already uses Bootstrap and jQuery. It seems like the JavaScript isn't affecting the HTML, which is driving me crazy. I've tried adding Bootstrap Switch using both the gem and stra ...

align the text below a single element

Whenever I attempt to designate the character c as sub-aligned within a table row, the subsequent bar text also becomes sub-aligned (which is very counterintuitive). <table> <tr> <td>test</td> <td>foo<sel style= ...

What is the best way to rearrange columns in bootstrapping version 3

In the process of developing a responsive website with the use of bootstrap 3, I am faced with the task of rearranging columns for the mobile version. The layout of the home page has been attached for reference, along with the desired layout for the mobi ...

The table in React does not update after sorting the elements in the state, causing the list to not re-render

I'm encountering a problem with React where the data is not rendering properly after sorting the table. Even though I am updating the state variable using setState, the new updated data does not appear on the screen. Here's the snippet of my code ...

What is the CSS method for styling a color label on an active input box?

I am trying to achieve a specific effect where the label changes color when the input box is in focus. However, my current CSS code does not seem to be working as expected. Can someone please explain why and provide a solution to fix this issue? .test-l ...

Discovering the method to identify the loading of images referenced through JSON data using AJAX

When a user visits a specific site on my web, a large number of images are loaded. To achieve this, I utilize a JSON file containing the image filenames and other pertinent information which is fetched through an AJAX call. The process unfolds as follows: ...

The JavaScript creates a select box, but the value does not get sent when the form is submitted

When a user selects a value from the first select box, a second select box is dynamically created using JavaScript. This JS triggers a PHP file to query a MYSQL database for relevant items based on the initial selection. The issue I am facing is that the ...

Preventing Safari 16 (macOS) from automatically selecting the current date in an HTML <input type="date"> field

I am encountering an issue with Safari where date fields are defaulting to today's date if no date is selected. I have tried various methods to make the field blank when no date is chosen, but so far, nothing seems to work. In all other browsers, the ...

Arrange your grid system with Bootstrap Vue

There is a dataset retrieved from an API, and each item will be displayed within a div using a v-for loop. The desired layout for the grid of divs is as follows: [-- item 1 --][-- item-2 --] [-- item 3 --][-- item-4 --] [-- item 5 --][-- item-6 --] [-- ite ...

Is it possible to combine the :last-child pseudo-class with the universal selector (*) in CSS or Sass

Here is the code I am currently using: .loken5 * padding-right: 5px .loken5:last-child padding: 0 I am wondering if there is a way in SASS to achieve the same effect with just one '.loken5' tag for saving space. Thank you :) ...

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I ne ...

Exploring the Motion of a Rolling Ball on an Incline - Interactive Animation Using HTML5 Canvas and JavaScript

Is there a way to replicate the motion of a ball moving down an inclined plane using HTML5 canvas and JavaScript? Does anyone have code examples demonstrating how this can be achieved? ...

Stop the Nav bar item from collapsing

Alright, let's talk about the scenario: The situation is that I have a basic, plain, nav nav-tabs navigation bar with a few elements and a rightmost item (with pull-right) positioned as an <li> element which includes a dropdown. As the window ...

Connecting CSS styles and images to my EJS templates on a distant Express server using Node.js (Ubuntu 18.04)

I have been hunting for a solution here extensively, but every attempt has failed. So, here's the issue I'm facing: I have created a basic Express server locally to display a static page until I finish full integration. The structure of my site ...