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.
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>
Use the position for child div so it will display exaclty horizontally and vertically center.
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;
width: 200px;
height: 200px;
position: absolute;
background: #eee;
border: 1px solid #000;
text-align: center;
padding: 20px;
}
<!-- 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With