rshah
rshah

Reputation: 691

Unable to center text inside an absolute positioned div

I have 2 divs, one called info-holder and the other called info-content.

Info-holder has relative positioning whereas info content has absolute positioning.

The content contains (or will eventually contain) paragraph and heading elements, but they are aligned left, when I want them to be aligned center.

Any idea how I can fix this?

Here is what I have so far: http://jsfiddle.net/2egL00y5/

Upvotes: 2

Views: 127

Answers (3)

lmgonzalves
lmgonzalves

Reputation: 6588

You need to add width: 100% to the elements:

.info-content {
    width: 100%;
}

h1 {
    width: 100%;
}

FIDDLE: https://jsfiddle.net/lmgonzalves/2egL00y5/1/

EDIT:

If you don't need the position: absolute, the only style that you need to apply is:

.info-content {
    text-align: center;
}

Removing also the styles in h1.

FIDDLE: https://jsfiddle.net/lmgonzalves/2egL00y5/4/

Upvotes: 3

Dmitriy
Dmitriy

Reputation: 4503

alternative - transform: translate

.info-holder {
	position: relative;
	height: 420px;
	max-height: 420px;
	width: 29%;
	display: inline-block;
	margin: 0 auto;
	padding: 0;
	text-align: center;
	background: rgba(0, 0, 0, 0.5);
}
.info-content {
	position: absolute; left: 50%;
	text-align: center;
    -webkit-transform: translate(-50%, 0);
    -ms-transform: translate(-50%, 0);
    transform: translate(-50%, 0);
}
h1 {
	margin: 0 auto;	
	text-align: center;
}
<div class="info-holder">
    <div class="info-content">
        	<h1>Hello</h1>
    </div>
</div>

Upvotes: 0

Kirk Powell
Kirk Powell

Reputation: 910

Here is what I did:

.info-holder {
    position: relative;
    height: 420px;
    max-height: 420px;
    width: 29%;
    margin: 0 auto;
    padding: 0;
    background: rgba(0, 0, 0, 0.5);
}
.info-content {
    text-align: center;
}
h1 {
    margin: 0 auto;
    display: inline-block;
}

Upvotes: 0

Related Questions