问题
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