Filipe Teixeira
Filipe Teixeira

Reputation: 499

How to center nested divs with rotation with CSS3?

I am trying to use css mix-blend-mode property to make a superposition of divs with difference, making a chess pattern. But my problem is how to center everything elegantly.

This is my code:

var n = 20;
var s = 300;

for (var x = 1; x < n; x++) {
  $("div").last().append("<div/>");
}

$("div").css({"transform": "rotate(" +  (360 / n) + "deg) translate(-30%, -30%)",
              "width": s,
              "height": s});
body {
  background-color: black;
  overflow: hidden;
}

div {
  mix-blend-mode: difference;
  background-color: white;
  position: absolute;
  top: 30%;
  left: 30%;
  border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Any ideas on how to center everything perfectly?

EDIT: I want that the hole of the chess donut be on the center of the page.

Upvotes: 2

Views: 217

Answers (1)

Max Starkenburg
Max Starkenburg

Reputation: 1539

Not sure if this 100% works for your case, but if you can put those divs in a container that is centered with absolute positioning relative to the page, then you can center the donut hole pretty easily. If s and translate values are constant, it would be something like this:

HTML:

<section>
<div></div>
</section>

CSS:

section {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -100px; /* half of s */
  margin-left: -100px; /* half of s */
}

div {
  mix-blend-mode: difference;
  background-color: white;
  position: absolute;
  left: 30%; /* same as translate value */
  top: 30%; /* same as translate value */
  border-radius: 50%;
}

Fiddle

Else you'd have to set them with JS, like so:

var n = 20;
var s = 200;
var t = "30%";
for (var x = 1; x < n; x++) {
  $("div").last().append("<div></div>");
}

$("div").css({"transform": "rotate(" +  (360 / n) +  "deg) translate(-" + t + ", -" + t + ")",
              "width": s,
              "height": s, 
              "left": t,
              "top": t});
$("section").css({"margin-left": s / -2 + "px",
                  "margin-top": s / -2 + "px"})

Fiddle

Upvotes: 1

Related Questions