0

What I now have is this:

<div class="columns">
            <h1>Text</h1>
            <img src="images/camera.jpg">

My CSS, I basically have 3 columns with an image in them using the img tag

.columns{
    float: left;
    width: 33.33%;
    margin-right: 0px;
}

.columns img{
    display: inline-block;
    width: 95%;
    margin: 20px;
 }

.columns h1{
    position: absolute;
    color: white;
    margin-top: 12px;
    z-index: 1;
}

How do I center the text in a column?

snocc
  • 1
  • 4
  • To reword it, you want your image to fill the column, and then have the heading cover that image, centred inside the column. Is that right? – chriskirknielsen Apr 22 '20 at 22:15
  • yes, this is what it currently looks like: https://imgur.com/a/mFMMawl (when you hover over it it becomes blurry that's why I put it's z-index to 1) – snocc Apr 22 '20 at 22:17

2 Answers2

1
  left:50%;
    transform: translateX(-50%);

solves your problem but also give container position as relative

.columns{
    float: left;
    width: 33.33%;
    margin-right: 0px;
    position:relative
}

.columns img{
    display: inline-block;
    width: 95%;
    margin: 20px;
 }

.columns h1{
    position: absolute;
    color: white;
    margin-top: 12px;
    z-index: 1;
    left:50%;
    transform: translateX(-50%);
 
    
}
<div class="columns">
            <h1>Text</h1>
            <img src="https://i.stack.imgur.com/oSLyH.jpg?s=48&g=1">
            </div>

and also another way

.columns h1{
    position: absolute;
    color: white;
    z-index: 1;
    left: 0;
    right: 0;
    margin: 0 auto;
    text-align:center;
    margin-top: 12px;
}
pc_coder
  • 12,891
  • 2
  • 18
  • 41
  • Thank you! Can you maybe explain what translateX means? I'm doing this for a school project and haven't learned these things yet. – snocc Apr 22 '20 at 22:26
  • translateX is repositioning element in 2d plane . U can check how it works here https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateX – pc_coder Apr 22 '20 at 22:30
0

To center it both horizontally and vertically

<div class="columns">
         <div class="subcol">
            <h1>Text</h1>
            <img src="images/camera.jpg">
         </div>
</div>
.columns{
    float: left;
    width: 33.33%;
    margin-right: 0px;
}

.columns img{
    display: inline-block;
    width: 95%;
    margin: 20px;
 }
.subdiv{
  position: relative;
}
.columns h1{
    position: absolute;
    color: white;
    z-index: 1;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
Eye Patch
  • 459
  • 7
  • 17