Search code examples
htmlcssresponsive-design

How do I give my text the same height as it's container?


This is my HTML:

<div class="bigcontainer">
    <div class="container">
      <div>hello</div>
    </div>
</div>

This is my CSS:

.bigcontainer {
  height: 20%;
  width: 100%;
} 

.container {
  height: 100%;
  width: 100%;
}

However, as my website is responsive, I would like the text "hello" to always have the same height as its parent container. How can I achieve this using CSS?


Solution

  • Try setting the height of the html,body element to 100% or You need to give the container a fixed value(bigcontainer).

    To make the text same height as it's container(bigcontainer). Get the container offsetHeight using javascript and assign it to the text as height and fontSize

    I have added two container (bigcontainer) heights, one being 20% and the other 50%, so that the text height and text size changes.

    Also i have added border:1px solid black to indicate the text height

    1. if you need only text height remove y.style.fontSize=x+'px' and yy.style.fontSize=xx+'px'

    2. if you need only text size (fontSize) remove y.style.height=x+'px' and yy.style.height=xx+'px'

    Check the following examples

    var x = document.getElementsByClassName('container')[0].offsetHeight;
    var y = document.getElementById('idname');
    y.style.fontSize=x+'px';
    y.style.height=x+'px';
    
    var xx = document.getElementsByClassName('container2')[0].offsetHeight;
    var yy = document.getElementById('idname2');
    yy.style.fontSize=xx+'px';
    yy.style.height=xx+'px';
    body,html {
      height:100%;
      margin:0;
      padding:0;
    }
    
    .bigcontainer {
      height: 20%;
      width: 100%;
    } 
    .container {
      width: 100%;
      height:100%;
    }
    .container div{
      height:100%;
      border:1px solid black;
    
    }
    
    .bigcontainer2 {
      height: 50%;
      width: 100%;
    } 
    .container2 {
      width: 100%;
      height:100%;
    }
    .container2 div{
      height:100%;
      border:1px solid black;
    
    }
    <div class="bigcontainer">
        <div class="container">
          <div id='idname'>hello</div>
        </div>
    </div>
    
    <div class="bigcontainer2">
        <div class="container2">
          <div id='idname2'>hello</div>
        </div>
    </div>