You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React实现左侧固定图片、右侧固定按钮的点餐布局解决方案

点餐布局:固定右侧添加按钮,文本自动换行

问题描述

开发点餐布局时,需要实现:

  • 左侧固定显示商品图片
  • 中间展示商品信息,文本过长时自动换行
  • 右侧固定放置「添加」按钮,不受中间文本长度影响

当前按钮会随中间文本长度变动位置,需要调整布局实现按钮固定在右侧。

修改后的代码

Foodlist.js(结构无需大改,仅优化图片alt属性)

import React from "react";
import "./Foodlist.css";
import { useStateValue } from "../../StateProvider";

function Foodlist({ id, title, rating, image, price, info, stock, nostock  }) {
 
  const [{ basket }, dispatch] = useStateValue();

  const addToBasket = () => {
      dispatch({
          type: "ADD_TO_BASKET",
          item: {
              id: id,
              title: title,
              info: info,
              image: image,
              price: price,
              stock: stock,
              nostock: nostock,
              rating: rating,
          },
      });
  };


  return (
    <div className="food">
      <div className="food__details">
        <img src={image} alt={title} />
      </div>

      <div className="food__title">
        <div className="food__info__layout">
          <p style={{fontWeight: "bold"}}>{title}</p>
          <p className="food__info">
            <small>₹ </small>
            <strong style={{fontSize: 14 ,fontWeight: 100}}>{price}</strong>
          </p>
        </div>

        <button onClick={addToBasket} style={{fontWeight: "bold"}}>
          <strong style={{fontSize: 20}}>+ </strong>
          Add
        </button>
        
      </div>
    </div>
  );
}

export default Foodlist

Foodlist.css(关键布局调整)

.food {
  display: flex;
  flex-direction: row;
  background-color: transparent;
  align-items: center;
  margin: 5px;
  width: 100%; /* 让容器占满父级宽度 */
}

.food__details{
  display: flex;
  flex-direction: row;
}

.food__details > img {
  max-height: 100px;
  width: 120px;
  object-fit: contain;
  margin-right: 10px;
  border: 1px solid gold;
  border-radius: 10px;
  overflow: hidden;
}

.food__info__layout {
  display: flex;
  flex-direction: column;
  flex: 1; /* 让文本区域占据中间所有可用空间 */
}

.food__info {
  display: flex;
  flex-direction: row;
  height: auto;
}

.food__title {
  display: flex;
  flex-direction: row;
  flex: 1; /* 占据图片之外的全部空间 */
  justify-content: space-between; /* 文本居左,按钮居右 */
  align-items: center; /* 垂直居中对齐 */
}

.food__title > button {
  background: gold;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  height: fit-content;
  width: fit-content;
  margin-left: 15px; /* 保持按钮和文本的间距 */
  white-space: nowrap; /* 防止按钮文字换行 */
}

关键修改说明

  • 给.food添加width: 100%,确保容器占满父级宽度,为flex布局提供足够空间
  • 设置.food__title为flex: 1,使其占据图片右侧的全部可用空间,并通过justify-content: space-between让中间文本和按钮分别对齐左右两侧
  • 给.food__info__layout添加flex: 1,让文本区域在空间不足时自动换行,同时保证按钮始终固定在右侧
  • 给按钮添加white-space: nowrap,避免按钮文字因空间过小而换行

内容的提问来源于stack exchange,提问作者ami_PBJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:37:53