Is there a CSS way to position an HTML element vertically following the golden ratio?

前端 未结 3 1408
后悔当初
后悔当初 2021-02-10 00:47

I want to position an HTML element in the horizontal middle and vertical golden ratio with CSS only. The height of the element must be absolutly flexible, so I can not just set

3条回答
  •  花落未央
    2021-02-10 01:47

    Finally I found an answer, after eight years :D

    Because of new CSS technologies :)

    see my CodePen: https://codepen.io/eHtmlu/pen/ExjZrQb

    or the same live example here on stackoverflow:

    /***********************************/
    /* Here is where the magic happens */
    .container {
      display: flex; /* we need the flex technique */
      flex-direction: column; /* and we need it vertically */
      align-items: center; /* horizontally we just center the box */
    }
    
    .container::before {
      content: " ";
      flex-grow: .38196601; /* This is the magic number that places the box vertically in the golden ratio */
    }
    /* That's it!! */
    /* except you want to place it relatively to the viewport - see below, where we position the container element */
    /***********************************/
    
    
    /* To place the container at the golden ratio of the viewport, we need to set the height of "html" and "body" to 100% and margin to 0. Then we use the same technique as we used for the box. */
    html,
    body {
      height: 100%;
      margin: 0;
    }
    
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    
    body::before {
      content: " ";
      flex-grow: .38196601;
    }
    
    
    /* The rest are just a few environmental and styling settings */
    
    .container {
      border: #000 solid 1px;
      height: 20em;
      width: 30em;
      margin: 0 auto;
    }
    
    .box {
      width: 10em;
      padding: 1em;
      border-radius: .5em;
      box-shadow: 0 0 1em rgba(0, 0, 0, .5);
      text-align: center;
    }
    This box is located vertically in the golden ratio of the container element.

提交回复
热议问题