incredible123
incredible123

Reputation: 123

How to center a div within a div but keep it responsive and have it stay in the center

I have stacked small a div on top of another div and I want the small div to be at the bottom and centered, like this: Style.

I've searched up answers but some answers are telling me to make the small div relative but I can't do that otherwise it wont stack on top of the other div. How can I achieve this?

Here is my sandbox which explains the problem: https://codesandbox.io/s/sweet-bas-grubn

Upvotes: 1

Views: 302

Answers (2)

Md.Emran Sikder
Md.Emran Sikder

Reputation: 61

You can try this one. I hope it will be helpful for you.

import "./styles.css";

export default function App() {
  return (
    <div
      style={{
        position: "relative",
        background: "blue",
        width: "100%",
        height: "400px",
        margin: "0px",
        padding: "0px"
      }}
    >
      <div
        style={{
          position: "absolute",
          background:"white",
          zIndex:1,
          height:"200px",
          width:"150px",
          bottom:"0",
          left:"40%"
        }}
      ></div>
    </div>
  );
}

enter image description here

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202605

Since you are using absolute positioning, set the bottom to 0, left to 50%, then translate it left by 50% of the width.

style={{
  position: "absolute",
  backgroundColor: "white",
  zIndex: 1,
  height: "250px",
  width: "40%",
  bottom: 0,                     // <-- 0px from bottom of screen
  left: '50%',                   // <-- 50% of parent div width from left
  transform: 'translateX(-50%)', // <-- translate left 50% of child width
}}

enter image description here

Upvotes: 1

Related Questions