Assign CSS variable to CSS property value of another CSS element with pure CSS?

问题: Assuming I have an element #banner with font-size: 36px; as shown in the Code Snippet below: #banner { font-size: 36px; width: 100%; background-...

问题:

Assuming I have an element #banner with font-size: 36px; as shown in the Code Snippet below:

#banner {
    font-size: 36px;
    width: 100%;
    background-color: red;
    text-align: center;
}
<div id="banner">
  <h1>Hello StackOverflow!!</h1>
</div>


How can I retrieve that 36px from #banner's css property font-size and assign it to a css variable so I can use the calc() function to dynamically set the font-size of another element, say #someOtherBanner to #banner's font-size value divided by say, 3 thus returning 12px.


A dummy representation of what I'm looking for can be seen in the Code Snippet below:

:root {
  --bannerFontSize: #banner.font-size;
}

#banner {
    font-size: 36px;
    width: 100%;
    background-color: red;
    text-align: center;
}
#someOtherBanner {
    font-size: calc(var(--bannerFontSize) / 3); // should return 12px
    width: 100%;
    background-color: green;
    text-align: center;
}
<div id="banner">
  <h1>Hello StackOverflow!!</h1>
</div>
<hr />
<div id="someOtherBanner">
  <h1>Hello from me too, StackOverflow!!</h1>
</div>


The closest thing I found that might help was the CSS attr() function that retrieves an attribute's value from HTML elements (one can use this to set elements' css properties to an attribute while simultaneously setting css variables to the attribute's value) but according to CanIUse.com, it is not compatible with any browser so far.

This would be a piece of cake using JavaScript or css preprocessors like SCSS but what would be the Vanilla CSS approach to do this?


回答1:

One thing you could do is simply use the same CSS variable as both the font-size in the banner and the padding in the secondary banner.

This would look like this:

:root {
  --bannerFontSize: 36px;
}

#banner {
  font-size: var(--bannerFontSize);
  width: 100%;
  background-color: red;
  text-align: center;
}

#someOtherBanner {
  padding: calc(var(--bannerFontSize) / 3);
  width: 100%;
  background-color: green;
  text-align: center;
}
<div id="banner">
  <h1>Hello StackOverflow!!</h1>
</div>
<hr />
<div id="someOtherBanner">
  <h1>Hello from me too, StackOverflow!!</h1>
</div>

Note that in your example you have a division by / 3px, whereas you want / 3.

  • 发表于 2019-01-15 10:48
  • 阅读 ( 150 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除