Reputation: 22659
Consider the following html:
<div class="image">
<img src="sample.png"/>
<div class="text">
Text of variable length
</div>
</div>
Where:
.image {
position:relative;
text-align:center; // doesn't work as desired :(
}
.text {
position:absolute;
top:30px;
}
Can you please tell, if there is a way to horizontally align the text in the center of the .image
div? I can't use the left
property, since the length of the text is unknown and the text-align
property doesn't work for the .text
div :(
Thank you.
Upvotes: 27
Views: 104521
Reputation: 131
Try this:
.image {
position:relative;
}
.text {
position: absolute;
top: 0;
left: 0;
width:100%;
height:100%;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
Upvotes: 13
Reputation: 1
Using Flex is a more"flexible" option :-)
#countdown {
font-size: 100px;
z-index: 10;
}
#countdown-div {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
#bg-image {
width: 100vw;
height: 100vh;
position: absolute;
top: 0px;
left: 0px;
}
<div>
<div id="countdown-div">
<h1 id="countdown">10</h1>
</div>
<img id="bg-image" src="https://lh3.googleusercontent.com/proxy/PKaxc9qp52MkavbkMnnbu0AZAGcqxJCoa7wIgtCmOr2e1x9ngdsteITX6x4JqDDFOhhdZmF79Ac5yevMGaUmcSaFnFYsHQtLPxHg56X_8PfP1fNkxMNXYd3EzhuCb3eJ2qQA">
</div>
Upvotes: 0
Reputation: 901
Try the following CSS:
.image {
position:relative;
}
.text {
left: 0;
position:absolute;
text-align:center;
top: 30px;
width: 100%
}
Upvotes: 67
Reputation: 253318
First you need to float the .image
element, in order to 'collapse' its block-level descendants to the width of the element, and then use text-align
on the .text
element:
.image {
float: left;
}
.text {
text-align: center;
}
Or you could simply give it a display: inline-block
, which will allow it to have its block-level contents contained, and remain in the document flow:
.image {
display: inline-block;
}
.text {
text-align: center;
}
Upvotes: 2
Reputation: 12574
Can you not use the image as the background image of the 'image' div using background-image: url('/yourUrl/'); and then rather than have your text in its own div simply place it in the image div and then apply text-align: center;
Upvotes: 1