Center block (paragraph) inside div

ⅰ亾dé卋堺 提交于 2019-12-24 19:09:06

问题


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?


回答1:


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;




回答2:


You should be able to just add display:table-cell; vertical-align:middle; to your cover price class.




回答3:


Have you tried Span and normal padding??

<p><span class="price">20.0 </span></p>

.cover-price p{
line-height: 50px;
width: 100%;
height: 50px;
/*background-color: rgba(43,32,122, .3);*/
color: pink;
padding-top : 45%;
position: relative;
}

.price{
background-color: rgba(43,32,122, .3);
}

http://jsfiddle.net/BZGhU/13/




回答4:


    .cover-price{
    height: 300px;
    width: 300px;
    background-repeat: no-repeat;
    background-size: cover;
    display:table-cell; vertical-align:middle;
}


来源:https://stackoverflow.com/questions/17584913/center-block-paragraph-inside-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!