首页 > 解决方案 > 如何在居中视频旁边的剩余空间中居中按钮

问题描述

我想用 CSS 做这个布局: 带红色按钮的居中视频

(其<video>纵横比和大小可能会改变)应在具有黑色背景的容器中垂直和水平居中(容器的大小也可能会改变)。<button>应位于 右侧剩余空间的中心<video>。如果按钮没有空间,它应该覆盖<video>.

我目前拥有的是这样的:

div {
  background-color: black;
  position: relative;
  resize: both;
  overflow: hidden;
}

video {
  display: block;
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
video:focus {
  outline: none;
}

button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 16px;

  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: red;
  border: 5px solid white;
}
<div style="height: 200px; width: 700px;">
  <video src="https://static.videezy.com/system/protected/files/000/019/696/pointing_blue.mp4" autoplay muted loop></video>
  <button></button>
</div>

但我不知道如何使按钮居中

标签: css

解决方案


关键词:

  • .button-spacer在视频的两侧添加元素 ( ) 以声明按钮所需的宽度。
  • 使用flex 布局均匀地居中和间隔所有内容。
  • absolute即使视频旁边没有足够的空间,也可以使用按钮上的定位将其保持在屏幕上。

.player {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-evenly;

  background-color: black;
  resize: both;
  overflow: hidden;
}

video {
  display: block;
  max-width: 100%;
  max-height: 100%;
  align-self: center;
}
video:focus {
  outline: none;
}

.button-spacer {
  flex: 1 1 auto;
  max-width: 50px;

  position: relative;
  display: flex;
  align-items: center;
  
  background: maroon;
}

button {
  position: absolute;
  right: 0;
  width: 50px;
  height: 50px;
  
  background-color: red;
  border-radius: 50%;
  border: 5px solid white;
  cursor: pointer;
}
<div class="player" style="height: 120px; width: 400px;">
  <div class="button-spacer"></div>
  <video src="https://static.videezy.com/system/protected/files/000/019/696/pointing_blue.mp4" autoplay muted loop></video>
  <div class="button-spacer">
    <button></button>
  </div>
</div>


推荐阅读