在标题中间垂直对齐 svg 图像 [复制]

Vertically align svg image in the middle of heading [duplicate]

提问人:lukaskupfing 提问时间:11/7/2023 最后编辑:lukaskupfing 更新时间:11/7/2023 访问量:51

问:

我正在尝试相对于标题垂直对齐指示器。指示器应水平对齐在标题的右侧,垂直对齐在标题的中间。当航向占据一行时,指标应进一步向下,当它占据两行时(例如,在较小的窗口中),应进一步向上。这是我的代码:

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>

为什么不起作用?vertical-align: middle;

HTML CSS格式

评论


答:

1赞 steveross 11/7/2023 #1

display: flex, position: relative是无稽之谈。请将这些样式移动到标签中。h1

h1 {
    border-bottom: 1px solid;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.indicator {
    float: right;
    width: 24px;
    height: 24px;
    margin-left: 20px;
}

评论

0赞 rozsazoltan 11/7/2023
避免使用浮点进行布局
1赞 Brett Donald 11/7/2023 #2

使用 flexbox 是实现所需目标的最简单方法,但需要在父元素 .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>