【问题标题】:CSS Height = Width?CSS 高度 = 宽度?
【发布时间】:2015-06-19 12:13:54
【问题描述】:

在 CSS 中执行此操作的简单方法是什么?

selector {
    width: 75%;
    height: width; 
}

我尝试将高度设置为各种属性,但它们似乎没有达到我想要的效果。如何将一个值设置为另一个值?

【问题讨论】:

  • 你不能在原版 CSS 中使用像 'width' 这样的变量。如果要使用动态值,请参阅calc 函数。
  • 你在寻找这样的东西吗:stackoverflow.com/q/5445491/1004522?
  • 我认为你需要像 SASS 或 LESS 这样的东西来使用变量。你可以用 JavaScript 做到这一点,但不确定你可以用 vanilla CSS。
  • 是的,我找到了答案。 stackoverflow.com/questions/5445491/…
  • 使用 JS 是可能的——但不是最好的方法。请参阅我的答案以获得更好的纯 CSS 解决方案。 K.s.和 GusP 是错误的。纯 css 是可能的。

标签: css height width


【解决方案1】:

我看到的最简单的方法是以这样的方式使用 jquery:

<html>
 <head>
  <script>
   selector{
    width: 75%;
   }
  </scipt>
 </head>
 <body>
  <script type="text/javascript" src="/jquery.js"></script>

  <selector></selector>
  <script type="text/javascript">
   $("selector").css("height", $("selector").width());
  </script>
 </body>
</html>

据我了解,这应该使宽度和高度均为 75%。

【讨论】:

    【解决方案2】:

    除了带有 CSS 变量的 firefox 之外,您目前不能使用 css

    http://caniuse.com/#feat=css-variables

    您可以使用像 less 或 sass 这样的动态样式表语言来编写带有变量的 css。然后,您可以将代码编译成纯 css。

    less 中的示例:

    @size: 75%;
    selector {
       width: @size;
       height: @size; 
    }
    

    【讨论】:

      【解决方案3】:

      上边距百分比基于宽度,因此使用纯 CSS 很容易计算。

      .wrapper {
        width: 50%;
        /* whatever width you want */
        display: inline-block;
        position: relative;
      }
      .wrapper:after {
        padding-top: 100%;
        /* 1:1 ratio, set from padding top being 100% */
        /* If you wanted one half as high, use 50% */
        
        display: block;
        content: '';
      }
      .main {
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        
        /* fill parent */
        background-color: red;
        
        /* let's see it! */
        color: white;
      }
      <div class="wrapper">
        <div class="main">
          This is a sample 1:1 responsive DIV. 
        </div>
      </div>

      【讨论】:

        【解决方案4】:

        好吧,如果您知道宽度 = 75%,那么您可以说高度 = 75%。

        selector {
            width: 75%;
            height: 75%;
        }
        

        现在,如果您使用 PHP/Javascript 更改宽度,也只需更改高度。这对我来说似乎是最简单的方法,但我对制作网站还是很陌生。

        这里也有回答:stackoverflow.com/q/5445491/1004522

        【讨论】:

          猜你喜欢
          • 2014-11-11
          • 2015-07-01
          • 2014-03-15
          • 1970-01-01
          • 1970-01-01
          • 2018-03-03
          • 2013-02-07
          • 1970-01-01
          • 2013-07-30
          相关资源
          最近更新 更多