Reputation: 1886
I have the following HTML/CSS code:
<style>.dummy {
color: greenyellow;
}
.middle-container {
position: absolute;
top: 50%;
left: 50%;
}
.middle-container-box {
width: 50px;
height: 50px;
background-color: red;
}
.middle-container-text {
color: red;
font-weight: bold;
font-size: 15px;
}
</style>
<html>
<body>
<div class="dummy">
Lorem Ipsum is simply dummy text...
</div>
<div class="middle-container">
<div class="middle-container-box"></div>
<div class="middle-container-text">
this text needs to be in the center
</div>
</div>
</body>
</html>
In this sandbox: https://codesandbox.io/s/2py075pqnr
I need to have middle-container
at the center of the screen and the div and the text elements (which are inside of this container) to be centralized inside of the container.
So it should be moved to the left, something as: https://prnt.sc/n349h1 (we need to move it only to the left). But moving it with fixes values (in pixels) is not an option, since I need this working on all screens resolutions.
Upvotes: 1
Views: 64
Reputation: 9739
You can do it with transfom
CSS
.dummy {
color: greenyellow;
}
.middle-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.middle-container-box {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
}
.middle-container-text {
color: red;
font-weight: bold;
font-size: 15px;
}
Upvotes: 1
Reputation: 121
Change .middle-container, set top, left, right, bottom to 0 then set margin to auto. Your text is already in the center because it's giving the div it's width, what you need to do is put .middle-container-box in the middle setting display to block and margin to 0 auto. See below:
.middle-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
.middle-container-box {
width: 50px;
height: 50px;
background-color: red;
display: block;
margin: 0 auto;
}
.middle-container-text {
color: red;
font-weight: bold;
font-size: 15px;
text-align: center;
}
Upvotes: 0
Reputation: 58462
You need to use translate to move to box back to the centre and flex to centre it's children:
.dummy {
color: greenyellow;
}
.middle-container {
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%, -50%); /* this moves this box back to the middle (back up and left 50% of itself) */
display:flex; /* the following four align it's children to the center horizontally and vertically */
flex-direction:column;
align-items:center;
justify-content:center;
}
.middle-container-box {
width: 50px;
height: 50px;
background-color: red;
}
.middle-container-text {
color: red;
font-weight: bold;
font-size: 15px;
}
<div class="dummy">
Lorem Ipsum is simply dummy text...
</div>
<div class="middle-container">
<div class="middle-container-box"></div>
<div class="middle-container-text">
this text needs to be in the center
</div>
</div>
Upvotes: 1