How to center paragraph vertically and horizontally w/ other criteria?

倾然丶 夕夏残阳落幕 提交于 2019-12-13 05:19:08

问题


So I have been working on my first website, and I'm having lots of fun doing it.

However, I have found it very difficult to achieve centering a paragraph (spanning more than one line) vertically and horizontally inside of it's div container.

The div has a proportional width (96%), and it is not set by pixels. Also, the paragraph has a set amount of padding (ex: 20px top and bottom).

Is there a trick to center vertically and horizontally in this situation?

Thanks a bunch!


回答1:


See this fiddle - http://jsfiddle.net/zv2Pu/1/

I have centered p both horizontally and vertically within the div container.

Hope this helps!




回答2:


From you 2 examples:

a single container inside a sized box:

you can use a pseudo to vertical-align pseudo and inside boxe aside each others DEMO

.holder {
    width: 96%;
    height: 400px;
    border: 1px solid black;
    text-align:center;
}
.holder:before {
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}
.holder p {
    display:inline-block;
    vertical-align:middle;
    width: 70%;
    margin: 20% auto;
    text-align:left;
}

A single or several boxes inside a sized box:

you can use display:table-cell; DEMO

.holder {
    width: 96%;
    height: 400px;
    border: 1px solid black;
    display:table-cell;/* it will expand if content grows oversized */
    vertical-align:middle;
}
.holder p {
    width: 70%;
    margin: 10px auto;
}
.holder div {
    width: 70%;
    margin: 10px auto;
}



回答3:


You could have simply used text-align: center; on your div.



来源:https://stackoverflow.com/questions/23667602/how-to-center-paragraph-vertically-and-horizontally-w-other-criteria

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