I have the following HTML/CSS where I try to center a div
with some <p>
to their parent div
wrapper. I tried to use the well known translate(-50%, -50%)
solution, but it does not work. I also tried to use margin: 0 auto
, also without success. I think I am missing a point, but I dont get it. Could someone tell me?
Hint: This is an MCVE constructed from only the relevant HTML and CSS rules, there are a lot of more so dont be confused about some display:block
or an !important
. I coloured the background and borders for better visualization.
Here is the snippet:
.half-width {
width:50%;
height: 795px;
}
div, p {
border: 1px solid red;
}
.container {
font-family: 'IBMPlexSans';
}
.container > div {
box-sizing:border-box;
border: 1px solid green;
background-color: inherit;
}
.container{
display:flex;
padding: 0;
width: 100%;
background-color: aqua;
flex-wrap: nowrap;
flex-direction: column;
}
.mobile-only{
display: block;
width: 100%;
}
/** for switching between mobile and desktop rules **/
.desktop-only{
display: none;
}
.background-black{
background-color: #4E4E4E !important;
width: 650px !important;
border-radius: 20px;
}
.size-35{
font-size: 35px;
height: 526px;
text-transform: uppercase;
}
.size-25{
font-size: 25px;
width: 335px;
height: 95px;
}
.size-19{
font-size: 19px;
width: 335px;
height: 350px;
margin-top: -25px;
}
/** center container div to an unknown body, works fine **/
.center-to-bg{
margin-left: auto;
margin-right: auto;
}
.height-495{
height: 495px;
}
.height-526{
height: 526px;
}
.desc-text > p{
display: block;
}
/** center the content div with the text to its parent,
horizontally AND vertically, does not work**/
.center-text{
position: relative;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.center-text > p{
display: block;
}
.center-h{
display: block !important;
left: 50%;
}
.half-width{
width: 100vw;
}
<div class="container">
<div class="half-width mobile-only background-black height-526 center-to-bg">
<div class="center-text color-white size-35" id="section2">
<p>ThIS IS </p>
<p>Á PARAGRAPH</p>
</div>
</div>
<div class="half-width mobile-only center-to-bg">
<div class="center-text color-white size-19">
<div class="desc-text">
<p>This is a long text that needs to be centered over multiple lines</p>
<p>
Because mobile devices are not that width
</p>
</div>
</div>
</div>
</div>