How do i place text in the middle of an image in html?

Viewed 92

This is my html code

<div class="container">
    <div class="box">
        <div class="content" style="display: flex">
            <img src="/img/logo.png">
            <p style="margin-left: 40px">YukinoMusic</p>
        </div>
    </div>
</div>

And the image below shows what I am trying to achieve

Here's the image

4 Answers

You need to use justify-content and align-items to manipulate the positioning of the children from .content selector. Set justify-content to left and align-items to center

.content {
  justify-content: left;
  align-items: center;
}

There are a few ways to do what you want

The best one is probably using your logo as a background image

.container {
  width: 100%;
  height: 130px;
  position: relative;
  background-image: url("https://i.stack.imgur.com/BjC4H.png");
  
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ccc;
  font-size: 2rem;;
}
<div class="container">
  YukinoMusic
</div>

But you can also use different divs and position them as you want

.content {
  position: relative;
}
#text {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  color: #ccc;
}
<div class="container">
  <div class="box">
    <div class="content">
      <img src="https://i.stack.imgur.com/BjC4H.png">
      <div id="text">YukinoMusic</div>
    </div>
  </div>
</div>

Technically, this is a CSS question, not a HTML question. CSS is concerned with the styling of your webpage, and therefore your question is in the realm of CSS, not HTML, which only describes content and structure.

The way I would do it is

  1. set the position attribute to absolute - this allows positioning outside of the normal flow of content
  2. place the left side of the text in the horizontal middle of its parent (in your case the div it is in)
  3. translate the text to the left by 50% of the width, to center the middle of the text, not the left side.

<p style="position: absolute; left: 50%; transform: translate(-50%)">"Hallo Welt"</p>

Here is how, just set the margin to be auto. Remember, first value is up&down and the second is left&right

margin: up&down left&right

body {
  background-color: rgb(40, 40, 40);
}

.content {
  border: solid white 2px;
  display: flex;
}

.content > img {
  border-radius: 50%;
}

.p1 {
  color: white;
  margin: 100px auto;
}

.p2 {
  color: white;
  margin: auto 200px;
<div class="container">
    <div class="box">
        <div class="content">
            <img src="https://i.pinimg.com/474x/63/a2/46/63a2469a6f9557da638b1c75d56b1554.jpg" width="200px">
             <p class="p1">YukinoMusic</p>
        </div>
        <div class="content">
            <img src="https://i.pinimg.com/474x/ab/63/55/ab63556093e53148bc947e63bb9b262a.jpg" width="200px">
            <p class="p2">YukinoMusic</p>
        </div>
    </div>
</div>

Related