Search code examples
htmlcssalignment

Center block (paragraph) inside div


There is example in JsFiddle .

Small description: Div is 300x300 but might be 500x500 or 100x100 in future (so need flexible solution) with background image (which is size:cover so don't care about size).

Inside this div there is <p> with hight of 50px (but might be 100px or 25px in future) which has text inside (20) and background-color that is a bit transparent (blue).

I want to center it inside this div and sollution should be flexible (so for future changes it won't be take a few hours to fix all images/ideas manually, so it would be cool to use % values.

Has anyone an idea?


Solution

  • One way:

    .cover-price{
        height: 300px;
        width: 300px;
        background-repeat: no-repeat;
        background-size: cover;
        position:relative; /*Make container relative*/
    }
    
    .cover-price p{
        line-height: 50px;
        width: 100%;
        height: 50px;
        background-color: rgba(43,32,122, .3);
        color: pink;
        position:absolute; /*make P absolute*/
        top: calc(50% - 50px); /*give top as 50% - height of p*/
    }
    

    Fiddle

    Using calc since you have specified css3 in tags

    If not using calc for lack of support below IE9 the you can specify the top value as height of the container/2-height of para i.e here top: 100px;