Reputation: 10661
I want to center a paragraph which is positioned absolute inside another div positioned relative. The problem is since this is absolute I can't use text-align: center! Also I want to center the paragraph both vertically and horizontally.. . My HTML looks like this
<div class="top">
<p class="same">Django</p>
</div>
CSS
.top
{
width: 100%;
height: 70px;
position: relative;
}
.same
{
position: absolute;
}
I want the paragraph text 'Django' to be in the center both vertically and horizontally (https://i.sstatic.net/ZXPJ5.jpg)
Upvotes: 3
Views: 3780
Reputation: 4431
You can achieve that in following way.
.top
{
width: 100%;
height: 70px;
position: relative;
}
.same
{
position: absolute;
height: 50%; /* This is mandatory i.e. this should not be auto */
text-align: center;
width: 70%; /*This is not mandatory*/
/* The code below is required to horizontally and vertically center the <p> element */
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
Upvotes: 0
Reputation: 44601
You don't need absolute positioning at all to achieve what you want :
.top { width: 100%; height: 70px; text-align: center; }
.same { display: inline; line-height: 70px; }
You can force paragraphs to have inline
layout and then center them horizontally using text-align: center
. To center them vertically just add line-height
to paragraph equal to container's height
(it is not a problem here as you container's height is fixed). If you don't want to set display: inline
explicitly, you can just use span
instead of p
.
Upvotes: 2