LoginSignup
2
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

モーダルサイズを自動で調整できるプロパティに出会って感動した

Posted at

はじめに

cssでモーダルを実装していた際に「fit-content」というプロパティに出会って感動したのでまとめておきたいと思います。fit-contentで子要素のサイズを元に親要素をリサイズしてくれます。

コードサンプル

モーダルのヘッダーに表示する文字列の長さに合わせて、モーダルのサイズを調整してくれるような動きを実装したコードになります。便利だ…。

hoge.jsx

const [isModalOpen, setIsModalOpen] = useState(false);
const [modalHaederText, setModalHaederText] = useState('');

{isModalOpen && (
  <div className="modal-overlay">
    <div
      className="hoge-modal"
      // fit-content
      style={{ width: 'fit-content', height: '70%' }}
    >
      <div
        className="hoge-modal-header"
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          width: '100%',
          marginRight: '50px',
        }}
      >
        <h2>
          {modalHaederText.length >= 10
            ? modalHaederText.slice(0, 10) + ''
            : modalHaederText}{' '}
          ヘッダーに表示する文字列
        </h2>
        <FontAwesomeIcon
          icon={faSquareXmark}
          className="close-button"
          onClick={() => setIsModalOpen(false)}
        />
      </div>
      // モーダルの中身を表示する処理
    </div>
  </div>
)}
style.css
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(128, 128, 128, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99;
}

.hoge-modal {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  max-width: 70%;
  max-height: 70%;
  border-radius: 15px;
  z-index: 101;
  display: flex;
  flex-direction: column;
}

.hoge-modal-header {
  padding: 15px;
  height: 15%;
  background-color: #0d74d3;
  border: solid;
  border-color: #0d74d3;
  border-width: 1px;
  border-radius: 15px 15px 0 0;
}

.hoge-modal-header h2 {
  line-height: 1;
  color: white;
  margin: 0;
}

.hoge-modal-header .close-button:hover {
  opacity: 0.8;
}

.hoge-modal-header .close-button {
  position: absolute;
  right: 0;
  padding: 5px;
  cursor: pointer;
  color: white;
  margin-right: 10px;
  font-size: 30px;
  transition: opacity 0.3s;
}

おわりに

普段はChakraUIを利用しているのですが、fit-contentに代替するプロパティはないようです。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0