0
I’m using Bootstrap 4 pro site development. I thought I’d start by including the basic grid structure along with the image and an H1 (to test positioning).
I wrapped the image and H1 in a div that I gave the class of img-ds
. This class contains a position: relative
and a display: inline-block
. On H1, I put a class I called texto-ds
containing a position: absolute
. After that, I thought if I used the parameters top: 50%
and left: 50%
, my text would be totally centered in the center, but I got this result, with the H1 leaning slightly to the lower right side (the X is roughly where I expected the H1 to be positioned):
Code HTML of this passage:
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 p-0">
<div class="img-ds">
<img class="img-fluid" src="img/bg-ds.jpg">
<h1 class="texto-ds">Teste</h1>
</div>
</div>
</div>
</div>
Code CSS of this passage:
.img-ds {
position: relative;
display: inline-block;
}
.texto-ds {
position: absolute;
top: 50%;
left: 50%;
color: white;
}
I made a codepen to facilitate your visualization. Note that at first hand, H1 is aligned to the correct center of the image. However, when the resolution is from a mobile device, H1 leans to the right side.
Wow! Thank you, you’re the best. But, one question: what is the function of the Transform property? How is it acting in this context? And why are the values negative? If I change the values of top and left, I will have to change the values of Transform as well?
– ChoiYun
The estate
transform
depending on the value passed can be used in the element to rotate, tilt, increase / scale down and etc access this link (https://developer.mozilla.org/en-US/docs/Web/CSS/transform) for more details. When it is placedtop: 50%
andleft: 50%
the<h1>
is centered on the parent element, note that you push the element right and down on50%
, because of this it seems that the element was not centralized, so it is usedtransform: translate(-50%, -50%);
in which the element will translate left and up centering the element.– user181348