Search code examples
htmlcsstextresponsivecentering

How can I center text (constantly) in a responsive manner?


I am pretty new to coding. I am learning HTML and CSS. I would like to know how I can make this title and subtitle centered in the four form factors (sizes I precized).

I am not sure why using white-spaceno wrap does not help :(

 .text-block {
        position: absolute;
        color: white;
        top: 10px;
        right: 50vh;
        left: 50vh;
        white-space:nowrap;
        
    
    }
    
    
    .thecloud {
      background: URL("https://picsum.photos/1920/1080");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      width: 100vh;
    }
    
    .container{
     position: relative;
    }
    
    .title{
    
      font-family: 'Poppins';
    
    }
    
    .subtitle{
    
      font-family: 'Poppins';
    
    }
   <div class="container">
          
          <picture>
            <img
              src="https://picsum.photos/1920/1080"
            />
          </picture>
        </div>
    
        <span style="text-align:center" class="text-block">
    
          <h1 class="title">Hubble Space Telescope</h1>
    
          <h2 class="subtitle">30 Years of Discovery</h2>
    
        </span>


Solution

  • You can achieve the centering of the text like this: (note: I changed your HTML a little bit.)

    .container{
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      position: relative;
    }
    .text-block{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
     <div class="container">
        <picture>
          <img alt="" src="https://picsum.photos/1920/1080"/>
        </picture>
        <span style="text-align:center" class="text-block">
            <h1 class="title">Hubble Space Telescope</h1>
            <h2 class="subtitle">30 Years of Discovery</h2>
        </span>
    </div>