如何用HTML和CSS制作一个对话框,在保持居中的同时自动缩小



我的目标是创建一个对话框,在移动设备上自动缩小以占据80%的屏幕空间,但在台式机或大型平板电脑上最大值为750px乘500px。这里有一个代码片段(我建议你点击完整页面(:

/* Just some styling to make stuff look nice */
body {
background: coral;
margin: 0;
}
div {
background: #4f00ff;
color: white;
font-family: sans-serif;
padding: 10px;
}
/* Question's focus code */
div {
position: absolute;
width: min(750px, 80vw);
height: min(500px, 80vh);
}
<html>
<body>
<div>
Dialog
</div>
</body>
</html>

然而,我似乎不知道如何将其居中。仅仅尝试这样做是不正确的:

/* Just some styling to make stuff look nice */
body {
background: coral;
margin: 0;
}
div {
background: #4f00ff;
color: white;
font-family: sans-serif;
padding: 10px;
}
/* Question's focus code */
div {
position: absolute;
width: min(750px, 80vw);
height: min(500px, 80vh);
left: min(calc((100vw - 750px) / 2), 10vw);
top: min(calc((100vh - 500px) / 2), 10vh);
}
<html>
<body>
<div>
Dialog
</div>
</body>
</html>

有什么方法可以在纯CSS中做到这一点吗?我是否必须使用媒体查询而不是实用程序minmaxclampcalc

根据我对你的问题的理解,你可以这样做。请确保在html中添加元标记。

body {
display: flex;
justify-content: center;
align-items: center;
background: coral;
height: 100vh;
}
div {
background: #4f00ff;
width: 750px;
height: 500px;
color: white;
font-family: sans-serif;
padding: 10px;
}
@media all and (max-width: 800px) {
div {
width: 80vw;
height: 80vh;
}
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
Dialog
</div>
</body>
</html>

有两种方法可以做到这一点。为了特别针对div,我指定了一个类"对话框";至分区

裕度:0自动

/* Just some styling to make stuff look nice */
body {
background: coral;
margin: 0;

}
.dialog {
margin: 0 auto;
width: min(750px, 80vw);
height: min(500px, 80vh);
background: #4f00ff;
color: white;
font-family: sans-serif;
}
<html>
<body>
<div class="dialog">
Dialog
</div>
</body>
</html>

或者,您可以使用flex,方法是将父项设置为display:flex并使用属性justify-content:center。

/* Just some styling to make stuff look nice */
body {
background: coral;
margin: 0;
display: flex;
justify-content: center;
}
.dialog {
width: min(750px, 80vw);
height: min(500px, 80vh);
background: #4f00ff;
color: white;
font-family: sans-serif;
}
<html>
<body>
<div class="dialog">
Dialog
</div>
</body>
</html>

使用最大宽度和类似的媒体查询,这是可能的。此外,填充物也干扰了它。

/* Just some styling to make stuff look nice */
body {
background: coral;
margin: 0;
}
div {
background: #4f00ff;
color: white;
font-family: sans-serif;
}

/* Question's focus code */
div {
position: absolute;
width: 80vw;
height: 80vh;
left: 10vw;
top: 10vh;
}
@media (min-width: 800px) {
div {
width: 750px;
left: calc((100vw - 750px) / 2);
}
}
@media (min-height: 550px) {
div {
height: 500px;
top: calc((100vh - 500px) / 2);
}
}
<html>
<body>
<div>
Dialog
</div>
</body>
</html>

最新更新