Center text within image

1

I need to align a text horizontally and vertically within an image.

Does any of you know how I can do this?

HTML

<img src="https://marketingdeconteudo.com/wp-content/uploads/2017/01/formatos-de-imagem-2.jpg">
    <p>Texto que deve ser alinhado!</p>
</img>

CSS

/* Não tenho a menor ideia do que fazer! */
    
asked by anonymous 16.03.2018 / 19:18

1 answer

1

Just to clarify, the <img> tag does not have to be closed, so this is wrong <img></img> (Image is an element of type "Void" it can not have anything inside, another example is <input> that also has no closing tag </input> )

Now about your question one of the options you can do is to put the image inside a <div> that is with display:flex and use the flex properties to align what is horizontal with justify-content:center and vertical with align-items:center

See the example:

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    display: flex;
    justify-content: center;
    align-items: center;
}
.holder {
    display: flex;
    justify-content: center;
    align-items: center;
}
.holder img, .holder p {
    position: absolute;
    font-size: 32px;
    font-family: sans-serif;
    text-align: center;
}
<div class="holder">
    <img src="https://marketingdeconteudo.com/wp-content/uploads/2017/01/formatos-de-imagem-2.jpg">
    <p>Texto que deve <br>ser alinhado!</p>
</div>
    
16.03.2018 / 19:48