简体   繁体   中英

set font-size of element to be multiple of a font-size of another element using JavaScript

Is it possible to set the font-size of an element to be a multiple of another element's font-size using JavaScript or CSS?

For example, if I have

.root {
   font-size: 10pt;
}

And I want to make the font-size another element to be multiple of this, so that it can be something like

.leaf {
   font-size: font-size-of-.root * 2.5;
}

I have tried this:

$(document).ready(function() {
        //var leaf = document.getElementsByClassName("leaf")[0];
        $('.leaf').css({
            "font-size": function() {
                return $(".root").css('font-size') * 2.5;
            }
        });
    });

But it is not setting the font-size accordingly.

Get the element's font-size using css() method and multiply it with the factor you want:

 $('.big').css('font-size', parseInt($('.small').css('font-size')) * 2.5 + 'px'); 
 .small { font-size:10px } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span class="small">Small font</span> <span class="big">Big font</span> 

You can also make .leaf a child of .root element -

<p class="root">
  Big
  <span class="leaf">Small</span>
</p>

And then use following css -

.root{
  font-size: 32px;
}
.leaf{
  font-size: 50%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM