-1

I'm having a scenario where the text has to be centered into a div which should have aspect ratio. I do not want to use aspect-ratio as a lot of main browsers like safari do not support that.

Here is my code on what I've done now:

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

.text{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    text-align: center;
    font-size: 20px;
    color: white;
}
<html>
  <div class="aspect-ratio-div">
    <label>This is some centered text</label>
  </div>
</html>

This would work fine for images, as I have learnt but what about for texts?

This is the output which I would like..

enter image description here

the white space should be in 1:3 ratio and the text always in center of it.

What would be a good approach ??

I got what I wanted thanks!!!

Aadhit Shanmugam
  • 433
  • 1
  • 10
  • 23

3 Answers3

1

You need to change your class to label bcos you have use label in HTML and some changes in CSS

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

label{
    position:  absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    font-size: 20px;
    color: #000;
}
<html>
  <div class="aspect-ratio-div">
    <label>This is some centered text</label>
  </div>
</html>
Aman
  • 1,502
  • 1
  • 8
  • 13
1

You can do this a few ways. Here are two.

.text does it with display: flex;
.text-asbolute does it with only absolute

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

.text{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 20px;
    color: black;
}

.text-absolute {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  color: black;
}
<html>
  <div class="aspect-ratio-div">
    <label class="text-absolute">This is some centered text</label>
  </div>
</html>
Dejan.S
  • 18,571
  • 22
  • 69
  • 112
1

There is the result with some changes over your code to make it work... I used Flex instead of transform to aproach the solution... this way you will not have problems with multiline texts (if needed).

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

.text {
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 20px;
    color: #000;
}
<html>
  <div class="aspect-ratio-div">
    <label class="text">This is some centered text</label>
  </div>
</html>
Tamplix
  • 53
  • 1
  • 7