skip to Main Content

I need to place several divs inside a container div. The main issue is the with of the container is 100% to fit the available space and the inner divs can overflow it.

The inner divs do have a fixed width and height.

The main requirement is the container div displays an horiz scrollbar if overflow.

I have this:

<div style={{ width: "70%", background: "azure" }}>
    <div
      style={{
        width: "100%",
        overflowX: "auto",
        display: "flex",
        border: "solid 1px #c1c1c1",
        padding: "5px"
      }}
    >
      {Array.from({ length: 10 }, (_, index) => (
        <div
          key={index}
          style={{
            width: "120px",
            height: "200px",
            border: "solid 1px",
            backgroundColor: "lightblue",
            marginRight: "5px"
          }}
        >
          Item {index + 1}
        </div>
      ))}
    </div>
  </div>

But instead of displaying the horizontal scrollbar it insists in resize divs. Here is the corresponding sandbox.

How can I solve this? What am I missing here?

2

Answers


  1. Set the flex-shrink CSS property to 0 so that the inner <div> elements do not shrink.

    <div
      key={index}
      style={{
        width: "120px",
        height: "200px",
        border: "solid 1px",
        backgroundColor: "lightblue",
        marginRight: "5px",
        flexShrink: 0
      }}
    >
      Item {index + 1}
    </div>
    
    Login or Signup to reply.
  2. add flexShrink: 0 style to the child elements
    the flex property is making the child to shrink as the shrink is set to 1 as default =, So make it 0

    <div style={{ width: "70%", background: "azure" }}>
        <div
          style={{
            width: "100%",
            overflowX: "auto",
            display: "flex",
            border: "solid 1px #c1c1c1",
            padding: "5px"
          }}
        >
          {Array.from({ length: 10 }, (_, index) => (
            <div
              key={index}
              style={{
                flexShrink: "0",// here
                width: "120px",
                height: "200px",
                border: "solid 1px",
                backgroundColor: "lightblue",
                marginRight: "5px"
              }}
            >
              Item {index + 1}
            </div>
          ))}
        </div>
      </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search