Home > Back-end >  Why can I not center vertically with parent height defined
Why can I not center vertically with parent height defined

Time:11-30

I am able to use the mx-auto class but I am unable to get the my-auto class to work despite my myContainerFixed class successfully showing the height as being fixed.

Example css


.mx-auto {
    margin-left: auto;
    margin-right: auto;
}

.my-auto {
    margin-top: auto;
    margin-bottom: auto;
}

.myContainerFixed {
    height: 90vh;
}
@screen lg {
    .myContainerFixed {
        height: 85vh;
    }
}

.w-max {
    width: max-content;
}

I also tried using absolute positioning even though this is definitely sub-optimal in this use case, but that didn't work either example below

.absoluteCenter {
  position: absolute;
  left: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%)
}

HTML Code

        return (
            <div className='bg-yellow-400 myContainerFixed'>
                <form onSubmit={handleSubmit(formFunction)} className=" bg-pink-400 w-max p-2 mx-auto my-auto rounded-sm [&>input]:mb-4  [&>label]:mr-2">
                    <label>Name</label>
                    <input type="text" {...register("name")} />
                    <div className='italic text-myDarkRed'>{errors.name?.message}</div>
                    <label>Email</label>
                    <input type="email" {...register("email")} />
                    <div className='italic text-myDarkRed'>{errors.email?.message}</div>
                    <label>Available Weights</label>
                    <input type="text" {...register("availableWeights", { setValueAs: (v: string | Array<number>) => Array.isArray(v) ? arrayToString(v) : v.split(",").map((weight) => Number(weight)) })} />
                    {/*  */}
                    <div className='italic text-myDarkRed'>{errors.availableWeights?.message}</div>

                    <button type="submit" className="p-2 rounded shadow-sm bg-gradient-to-b from-myRed to-red-400">Submit</button>
                </form>
            </div>
        );

CodePudding user response:

It has something to do with the top element (myContainerFixed) having display: block (default).

giving it for example display: flex; will fix this issue

.myContainerFixed {
    display: flex;
    height: 90vh;
}

i'd suggest to remove the mx-auto and my-auto and position the form using the flex props

.myContainerFixed {
    height: 90vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

  • Related