【问题标题】:Fit rotated square in parent square?在父正方形中适合旋转正方形?
【发布时间】:2017-10-21 03:52:10
【问题描述】:

我想创建一个占容器 50% 的正方形(以及自动高度?)。在这个正方形中,我想要一个旋转的正方形,它的点接触父母的边界(没有溢出)。它还必须具有响应性。

.square {
    height: 50%;
    width: 50%;
    .square-inner {
        transform: rotate(45deg);
        background: red;
        height: ??:
        width: ??;
    }
}

【问题讨论】:

    标签: css sass mixins


    【解决方案1】:

    你可以使用 position relative 和 absolute 和百分比来绘制它

    请参阅以下内容:

    .square {
        width: 50%;
        padding-top: 50%;
         background:blue;
         position: relative;     
    }
     .square-inner {  
            transform: rotate(45deg);
            background:red;
            height: 70%;
            width: 70%;
            margin:auto;
           position: absolute;
      top:15%;
      left:15%;
        }
    <div class="square">
    <div class="square-inner">
    
    
    </div>
    
    </div>

    【讨论】:

      【解决方案2】:

      如果x 是外正方形的边长,则sqrt(2)/2 * x (≈ 0.707x) 应该是内正方形的边长。 (more about the math)

      在 sass 中没有 sqrt 函数,我们可以这样估计它(more math):

      @function sqrt($square, $tolerance: .001, $estimate: $square/2) {
         @if abs($square - $estimate*$estimate) < $tolerance {
            @return $estimate;
         }
         @return sqrt($square, $tolerance, ($estimate + $square/$estimate)/2);
      }
      

      你的 sass 将是:

      $size: 200px;
      $halfSqrt2: sqrt(2)/2;
      
      .square {
          height: $size;
          width: $size;
          background: pink;
          display: flex;
          justify-content: center;
          align-items: center;
          .square-inner {
              transform: rotate(45deg);
              background: red;
              height: $halfSqrt2 * $size;
              width: $halfSqrt2 * $size;
          }
      } 
      

      PS:

      width: 50%;
      height: 50%;
      

      除非容器是正方形,否则不会给你正方形。

      【讨论】:

      • 我选择了上面的答案,但感谢您的回答!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      相关资源
      最近更新 更多