Home  >  Q&A  >  body text

Why am I still unable to achieve vertical centering despite setting the height of the parent element?

I am able to use the mx-auto class, but although my myContainerFixed class successfully displays a fixed height, I cannot get the my-auto class to work .

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;
}

Although this is certainly not the best option in this case, I also tried using absolute positioning, but that didn't work either Here is an example

.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>
        );

P粉493534105P粉493534105379 days ago507

reply all(1)I'll reply

  • P粉106711425

    P粉1067114252023-09-12 16:13:29

    It is related to the display: block (default) of the top element (myContainerFixed).

    For example, giving it display: flex; will fix this

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

    I recommend removing mx-auto and my-auto and using the flex attribute to position the form

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

    reply
    0
  • Cancelreply