The default behavior of the element is that it centers in the middle of the screen but I want it to center inside a container that it is in instead.
In the example below I have set #container with flex to center the dialog box but it doesnt affect the positioning at all, I also put some text inside just to check that it was working properly.
- How do I position the dialog in the middle of its parent container?
- It seems that using flex (or any display type) on the dialog box itself to position elements inside of it causes it to automatically reveal itself, is there a way to use flex without making it reveal itself (also the positioning of when this happens is different to when it is manually opened? You will see when you press the button)
I have tried using position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
too but that doesn’t work either.
const showButton = document.getElementById("showDialog");
const favDialog = document.getElementById("favDialog");
// "Show the dialog" button opens the <dialog> modally
showButton.addEventListener("click", () => {
favDialog.showModal();
});
.container {
display: flex;
justify-content: center;
align-items: center;
border: solid red 2px;
width: 700px;
height: 700px;
}
#favDialog {
display: flex;
/* position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); */
}
<!-- A modal dialog containing a form -->
<p>
<button id="showDialog">Show the dialog</button>
</p>
<div class="container">
<p> Dolore commodo cupidatat excepteur tempor irure amet aliquip amet commodo in ipsum ut ipsum occaecat.</p>
<dialog id="favDialog">
<h3>Title</h3>
<p>Dolore fugiat aliquip sint dolor elit dolore labore.</p>
<p>Labore incididunt id laborum occaecat.</p>
</dialog>
</div>
2
Answers
Use the position for child div so it will display exaclty horizontally and vertically center.
You can limit an elements positioning by giving the parent a position of relative and the child a position of absolute.
Example:
That will prevent the child element from going outside of the parent, because it makes the child element’s position dependent on the parent instead of the body.
If you want more info, I’d start here: https://css-tricks.com/absolute-positioning-inside-relative-positioning/