我有以下代码:

  <div class="details"><button className="details-btn"></button>
  <div>
  <p className="title">Some content
  </p>
  </div>

具有以下样式

.details {
  display: flex
}

button::before {
  content: url('data:image/svg+xml; utf8, <svg width="13" height="14" viewBox="0 0 13 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4.38128 4.61866L5.61872 3.38123L9.23743 6.99994L5.61872 10.6187L4.38128 9.38123L6.76256 6.99994L4.38128 4.61866Z" fill="black"/></svg>')
}

我想要居中的图像来自::before与段落.问题是,即使我的SVG的高度是14,得到的::before元素的高度是15.我为什么以及如何解决这个问题(我必须使用::before)

推荐答案

在css中,按钮的尺寸被设置为与图像匹配,并且它的位置是相对的.::BEFORE伪元素绝对位于按钮内,其背景图像使用变换和背景属性居中.这可确保图像与段落对齐.

function toggleOpen(button) {
  button.classList.toggle('is-open');
}
.details {
  display: flex;
  align-items: center; /* Vertical center alignment */
  gap: 5px;
}
button{
  position: relative; /* Add relative positioning */
  width: 13px; /* Set width of button */
  height: 14px; /* Set height of button */
  border: none;
  background-color: transparent;
  transition: transform 0.3s ease; /* Adding a transition for smooth animation */
}
button::before {
  background-image: url('data:image/svg+xml; utf8, <svg width="13" height="14" viewBox="0 0 13 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4.38128 4.61866L5.61872 3.38123L9.23743 6.99994L5.61872 10.6187L4.38128 9.38123L6.76256 6.99994L4.38128 4.61866Z" fill="black"/></svg>');
background-repeat: no-repeat; /* Prevent image from repeating */
  content: ''; /* Clear default content */
  position: absolute; /* Position the pseudo-element */
  top: 50%; /* Position it vertically */
  left: 50%; /* Position it horizontally */
  transform: translate(-50%, -50%); /* Adjust positioning */
  width: 13px; /* Set width of image */
  height: 14px; /* Set height of image */
  transition: transform 0.3s ease; /* Adding a transition for smooth animation */
}
button.details-btn.is-open::before {
transform: translate(-50%, -50%) rotate(90deg); /* Rotate the arrow icon when the button has is-open class */
}
<div class="details">
  <button class="details-btn" onclick="toggleOpen(this)"></button>
  <div>
    <p class="title">Some content</p>
  </div>
</div>

Html相关问答推荐

使用tauri构建的Next.js应用程序不显示我的404页面

CSS/添加margin—top到嵌入式facebook帖子

如何将FlexBox项目zoom 到其包含图像的大小

选中/取消选中带有_hyperscript的多个复选框

如何在一行文本溢出省略号后显示文本?

Div中的图像问题-(TailWind CSS中的网格)

从网页中提取URL

你将如何为手机制作导航栏

使用bash从html表格中提取表格

如何使用 HTML 将对象数组发送到 Nodejs Express

如果使用复选框属性更改,如何防止事件更改?

如何使用javascript在jsx中重复插入特殊字符?

CSS flex:0 0 auto创建了1像素的间隙

本地和在jsfiddle上页面工作正常,但在GitHub上无法运行.

如何从另一个 ng-template 获取输入值

将 div 放在图片旁边而不是下方

在 React (NEXT) 中,当我try 进行动态补充时,我无法使用实例this来引用输入

调整大小时 CSS 溢出

CSS 网格自动高度不适用于特定网格区域