首页 > 解决方案 > 如何使用 CSS 网格将按钮永久定位在底行

问题描述

我正在使用 CSS Grid 为布局制作一个简单的计时器应用程序。用户可以选择单击Add Timer按钮来创建新计时器。我希望按钮位于最后一行的中心。我如何实现这一目标?我尝试使用该grid-row属性,但是当我希望它是动态的时,我必须设置一定数量的行,相对于用户选择拥有的计时器数量。这是我的代码:

.wrapper {
  background-color: rgb(238, 238, 238);
  width: 100vw;
  height: 100vh;
  display: grid;
  align-items: center;
  justify-content: center;
}

.timers-container {
  background-color: white;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  align-items: center;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034),
    0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06),
    0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086),
    0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 1em;
}

.add-button {
  grid-column: 2/ 3;
  height: 40%;
  font-size: 2em;
  border-radius: 3em;
}
import React, { useState } from 'react';
import Timer from '../Timer/Timer';

import './Stopwatch.css';

function Stopwatch() {
  const [timers, setTimers] = useState([<Timer />]);

  const addTimer = () => {
    const timer = <Timer />;
    let allTimers = timers.slice();
    allTimers.push(timer);
    setTimers(allTimers);
  };

  return (
    <div className='wrapper'>
      <div className='timers-container'>
        {timers}
        <button className='add-button' onClick={addTimer}>
          Add Timer
        </button>
      </div>
    </div>
  );
}

export default Stopwatch;

这就是它的外观。如您所见,按钮的移动取决于定时器的数量:

在此处输入图像描述 在此处输入图像描述

标签: cssreactjscss-grid

解决方案


推荐阅读