I’m trying to create a layout where a red circle appears behind a gray circle using CSS. However, the z-index seems not to be working as expected. Here’s my CSS code:
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
div {
position: relative;
width: 300px;
height: 300px;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
/* Changed to 50% for a perfect circle */
}
div::before {
content: "";
position: absolute;
width: 300px;
height: 300px;
top: 0;
left: 0;
background-color: red;
border-radius: 50%;
/* Changed to 50% for a perfect circle */
z-index: -1;
/* This will send it to the back */
}
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div></div>
</body>
</html>
Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The Red circle is indeed behind the grey circle the reason you are not Abel to see it is because they are both of the same size. I reduced the size and added margin: auto to center the red circle just to show u that the red circle was always there. You could revert the z-index back to move the red circle being the grey circle.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
div {
position: relative;
width: 300px;
height: 300px;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%; /* Changed to 50% for a perfect circle */
}
div::after {
content: "";
position: absolute;
width: 150px;
height: 150px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background-color: red;
border-radius: 50%; /* Changed to 50% for a perfect circle */
z-index: 1;
}
1