skip to Main Content

I’m trying to align an indicator vertically relative to the headings. The indicator should be aligned on the right of the heading horizontally and in the middle of the heading vertically. When the heading takes up one line, the indicator should be further down, when it takes up two lines (e.g. in a smaller window), further up. Here’s my code:

h1 {
    border-bottom: 1px solid;
}

.indicator {
    display: flex;
    float: right;
    width: 24px;
    height: 24px;
    margin-left: 20px;
    position: relative;
    align-items: center;
    vertical-align: middle;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>This is a title</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>
    Heading 1
        <svg src="http://www.w3.org/2000/svg" class="indicator">
            <path d="m16.01 7.43-1.4-1.41L9 11.6 3.42 6l-1.4 1.42 7 7 7-7Z"></path>
        </svg>
    </h1>
    <h1>
    The quick brown fox jumps over the lazy dog
        <svg src="http://www.w3.org/2000/svg" class="indicator">
            <path d="m16.01 7.43-1.4-1.41L9 11.6 3.42 6l-1.4 1.42 7 7 7-7Z"></path>
        </svg>
    </h1>
    <h1>
    Heading 1
        <svg src="http://www.w3.org/2000/svg" class="indicator">
            <path d="m16.01 7.43-1.4-1.41L9 11.6 3.42 6l-1.4 1.42 7 7 7-7Z"></path>
        </svg>
    </h1>
    </h1>
</body>
</html>

Why doesn’t vertical-align: middle; work?

2

Answers


  1. display: flex, position: relative is nonsense. Please move these styles to h1 tag.

    h1 {
        border-bottom: 1px solid;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .indicator {
        float: right;
        width: 24px;
        height: 24px;
        margin-left: 20px;
    }
    
    Login or Signup to reply.
  2. Using flexbox is the easiest way to achieve what you want, but it needs to be set on the parent element, the h1.

    h1 {
      border-bottom: 1px solid;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 1em;
    }
    
    h1>svg {
      width: 24px;
      height: 24px;
      flex-shrink: 0;
    }
    <h1>
      Heading 1
      <svg>
        <path d="m16.01 7.43-1.4-1.41L9 11.6 3.42 6l-1.4 1.42 7 7 7-7Z"></path>
      </svg>
    </h1>
    
    <h1>
      The quick brown fox jumps over the lazy dog
      <svg>
        <path d="m16.01 7.43-1.4-1.41L9 11.6 3.42 6l-1.4 1.42 7 7 7-7Z"></path>
      </svg>
    </h1>
    
    <h1>
      Heading 1
      <svg>
        <path d="m16.01 7.43-1.4-1.41L9 11.6 3.42 6l-1.4 1.42 7 7 7-7Z"></path>
      </svg>
    </h1>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search