Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

css - How to make font-size relative to parent div?

I want text inside my div to remain same size in % percentage ratio to a parent div. I.E. I want my text to have font-size of 50% of parents div width. So when page size is changing, text always remains the same size in %.

Here Is what I'm talking about:

.counter-holder{
display: block;
position: absolute;
width:90%;
height:20%;
top: 70%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}


.counter-element-box{
position:relative;
vertical-align: text-top;
border-style: solid;
    border-width: 1px;
    width: 20%;
    height: 100%;
    float:left;
    margin: 6%;
}

.counter-element-text{
position:absolute; 
top:50%; 
width: 50%;
max-width:50%;
display: inline-block;
height:100%;
margin-left:50%;
font-size : 80%;overflow: hidden;
}

.counter-element-value{
position:absolute; 
top:50%; 
width: 50%;
max-width:50%;
display: inline-block;
height:100%;
padding-left:30%;
font-size : 80%;overflow: hidden;
}
<div class="counter-holder">
<div class="counter-element-box">
<div id="years" class="counter-element-value">
0
</div>
<div class="counter-text counter-element-text" >
    Years
</div> 
</div>
<div class="counter-element-box">
<div id="missions" class="counter-element-value">
0  
</div>
<div class="counter-text counter-element-text" >
    Missions
</div>
</div> 
<div class="counter-element-box">
  <div id="team" class="counter-element-value">
   0 
  </div>
  <div class="counter-text counter-element-text" >
    Team
  </div>
</div>    
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The way I solved this problem was to use javascript to measure the container and then set the font size in px on that container. Once that baseline is set for the container then the relative font sizing of all the content will scale correctly using em or %.

I'm using React:

<div style={{ fontSize: width / 12 }} >
  ...
</div>

CSS:

div {
  font-size: 2em;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...