Center a div with text and position Absolute in the center of div pai

Asked

Viewed 6,376 times

1

People is the following I have a father div and another div with a text in position Absolute... this text is aligned to the top and left of the father div and I need to align to the center... things like top: x% or left x% .. They work because the parent element is dynamic and responsive ...I need it to stay right in the center. I tried things like Justify content and align items in the center but it didn’t help.. someone knows how to... follow the code of the div :

.textotoposobre{
    text-align: center;
    color: white;
    font-family: 'Open Sans';
    align-items: center;
    justify-content: center;
    top: 30%;
    left: 28%;
}
  • A very useful site to learn how to center elements and text in CSS is <a href="http://howtocenterincss.com/">howtocenterincss.com</a>. It allows you to choose the height and width of the element, the alignment of content and what versions of internet explorer you need the code to work.

  • I’ll take a look obg

2 answers

5

Creating a div father with position: relative, and the div son with position: absolute must solve their problem, provided that the div child is positioned at a distance equivalent to 50% of the container (div father) less than half his own size. This distance should be worth both up and to the left. This can be accomplished as follows:

.filho{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

See that, this way, the size of the div father doesn’t matter.

.filho{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.pai{
    position: relative;
    width: 300px;
    height: 300px;
    background-color: aqua; 
}
<div class="pai">
    <div class="filho">Texto texto texto</div>
</div>

Try changing the size of div father to understand behavior.

  • thanks I’ll try here

0

In the div of the text put **margin: 0 auto;**

  • I think that as it has position: absolute; will center nothing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.