germainelol
germainelol

Reputation: 3331

Centering 2 text elements on top of an image

I'm trying to center these 2 text elements but having trouble. I have no trouble centering both elements just using text-align:center;, but I actually want the sub-heading and heading to both start from the same point. So it should look sort of like this below, where the heading text is directly in the center. I hope I've made myself clear, I can provide a picture if necessary.

I should mention that these divs are responsive, so it would have to apply to any size not just "put left: 50%" or something like that :P

            sub-heading
            heading text here


<div>
  <img class="center-block" src="img/shop-1.jpg">
  <span>
    <p class="sub-heading">sub-heading</p>
    <p class="heading">heading text here</p>
  </span>
</div>

CSS:

.shop span {
    position: absolute; 
    top: 30%; 
    left: 0;
    width: 100%; 
}

.shop span p {
    padding: 0;
}

.shop span .heading {
    color: #fafafa;
    font-size: 40px;
    text-shadow: 0 0 10px #ecd781, 0 0 20px #ecd781, 0 0 40px #ecd781, 0 0 80px #ecd781;
    /*text-shadow: 0 0 5px #ecd781;*/
    font-weight: 500;
}

Upvotes: 0

Views: 73

Answers (4)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Change your .shop span CSS as follows:

.shop span {
  position: absolute; 
  top: 30%; 
  left: 50%;
  transform: translatex(-50%);
  white-space: nowrap;
}

This will cause it to be centered based on the largest of the two headings. (If sub-heading is wider than heading, this won't meet your requirement.)

Fiddle

Upvotes: 2

Anarion
Anarion

Reputation: 1038

You may wrap text with an extra div with the following styling:

display:inline-block; text-align:left

Demo: http://codepen.io/Nargus/pen/jEgVMb

Wrapper element will be centered by outer text-align:center; rule, but inside it you'll have text-align:left; It is a much better way than fixed width and margin:auto; for centering

Upvotes: 1

Dashovsky
Dashovsky

Reputation: 137

Have you tried positioning your P classes using relative? It could work.

PS: your img tag isn't closed, insert / before >

Upvotes: 0

Cagatay Ulubay
Cagatay Ulubay

Reputation: 2559

Wrap both inside an <div> and than use following CSS for the <div>

div {
    width: 250px; /* Or the maximum of the wides text */
    margin: 0 auto;
}

This will position the div into the center, but let the text be left sided. If the width of the <div> is only max width of the wides text, it should fit.

Fiddle: http://jsfiddle.net/xLgxsme7/

edit

If you want to use your <span> than you have to make it display: block;, because you can't change the width of an inline-element.

Upvotes: 0

Related Questions