Home > Software design >  Center span of h1 relative to parent
Center span of h1 relative to parent

Time:11-22

My goal is to be able to center the "Animal Wildlife" relative to the container while the span still stays on the left side .

<div class="container">
<h1><span>Subscribe to </span>Animal Wildlife</h1>
</div>

How can I center part of the h1 while keeping the structure?

CodePudding user response:

center object

.container1 {
  display: flex;
  justify-content: center;
  /* center horizontal */
  align-items: center; /* center vertical */
}


/* --------------------------------- */

.container2 {
  width: 100%;
  height: 100%;
}

.container2 h1 {
  width: fit-content;
  margin: auto; /* center both */
}


/* --------------------------------- */

.container3 {
  position: relative;
}

.container3 h1 {
  width: fit-content;
  position: absolute;
  left: 50%; /* center left */
  top: 50%; /* center top */
  transform: translate(-50%, -50%); /* center object */
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <div class="container1">
    <h1><span>Subscribe to </span>Animal Wildlife</h1>
  </div>

  <div class="container2">
    <h1><span>Subscribe to </span>Animal Wildlife</h1>
  </div>

  <div class="container3">
    <h1><span>Subscribe to </span>Animal Wildlife</h1>
  </div>
</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I wasn't totally clear on your issue, but maybe this helps? Run the snippet below.

    <html>

    <head>
      <style>
        body {
          padding: 0;
          margin: 0;
        }

        .container {
          display: flex;
          justify-content: center;  
          color: #fff;
          background-color: #000;
          padding: 12px 24px;
          font-family: sans-serif;
        }

        h1 span {
          font-size: 12px;
        }
      </style>
    </head>

    <body>

      <div class="container">
        <h1>
          <span>Subscribe to</span><br>Animal Wildlife
        </h1>
      </div>

    </body>

    </html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related