Elemente auf einem Kreis platzieren

Avatar of Kitty Giraudel
Kitty Giraudel am

Es kann eine ziemliche Herausforderung sein, Elemente mit CSS auf einem Kreis zu platzieren. Normalerweise greifen wir auf JavaScript zurück, weil einige Plugins alles sofort richtig machen. Aber meistens gibt es keinen guten Grund, es statt mit CSS mit JavaScript zu tun. Dies dient der Darstellung, also gehen wir den CSS-Weg.

Der Mixin

Ana Tudor erklärte, wie sie es in einer Stack Overflow-Antwort mit verketteten CSS-Transformationen geschafft hat. Danach habe ich ihre Lösung in einen Sass-Mixin umgewandelt, um alles zum Kinderspiel zu machen.

/// Mixin to place items on a circle
/// @author Kitty Giraudel
/// @author Ana Tudor
/// @param {Integer} $item-count - Number of items on the circle
/// @param {Length} $circle-size - Large circle size
/// @param {Length} $item-size - Single item size
@mixin on-circle($item-count, $circle-size, $item-size) {
  position: relative;
  width:  $circle-size;
  height: $circle-size;
  padding: 0;
  border-radius: 50%; 
  list-style: none;       
  
  > * {
    display: block;
    position: absolute;
    top:  50%; 
    left: 50%;
    width:  $item-size;
    height: $item-size;
    margin: -($item-size / 2);
  
    $angle: (360 / $item-count);
    $rot: 0;

    @for $i from 1 through $item-count {
      &:nth-of-type(#{$i}) {
        transform: 
          rotate($rot * 1deg) 
          translate($circle-size / 2) 
          rotate($rot * -1deg);
      }

      $rot: $rot + $angle;
    }
  }
}

Vorsicht! Vendor-Präfixe wurden aus diesem Code-Snippet weggelassen. Achten Sie darauf, transform zu präfixen, wenn Sie Autoprefixer nicht verwenden.

Demo

Zu Demozwecken betrachten wir eine Liste von 8 Bildern, aber grundsätzlich könnte alles funktionieren.

<ul class='circle-container'>
  <li><img src='http://lorempixel.com/100/100/city' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/nature' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/abstract' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/cats' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/food' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/animals' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/business' alt="..." /></li>
  <li><img src='http://lorempixel.com/100/100/people' alt="..." /></li>
</ul>
.circle-container {
  @include on-circle($item-count: 8, $circle-size: 20em, $item-size: 6em); 
  margin: 5em auto 0;
  border: solid 5px tomato;
  
  img { 
    display: block; 
    max-width: 100%; 
    border-radius: 50%;
    filter: grayscale(100%);
    border: solid 5px tomato;
    transition: .15s;
    
    &:hover,
    &:active {
      filter: grayscale(0);
    }
  }
}