专业编程基础技术教程

网站首页 > 基础教程 正文

「CSS」 position:fixed 定位实现 模态框弹窗浮动垂直水平居中

ccvgpt 2024-07-19 12:58:50 基础教程 16 ℃

# flex 模态框弹窗浮动垂直水平居中

- position:fixed 定位

「CSS」 position:fixed 定位实现 模态框弹窗浮动垂直水平居中

- 元素的位置相对于浏览器窗口是固定位置。

- 即使窗口是滚动的它也不会移动;

HTML 代码实例

```html

<div class="modal">

<!-- 半透明的蒙板遮罩盖住模态框弹层的后面内容 -->

<div class="modal-backdrop"></div>

<!-- 主体 -->

<div class="modal-body">

<!-- 关闭 -->

<button class="close">关闭</button>

<form action="" method="post">

<table>

<caption>

用户登录

</caption>

<tr>

<td><label for="email">邮箱:</label></td>

<td><input type="email" name="email" id="email" /></td>

</tr>

<tr>

<td><label for="password">密码:</label></td>

<td><input type="password" name="password" id="password" /></td>

</tr>

<tr>

<td></td>

<td><button>登录</button></td>

</tr>

</table>

</form>

</div>

</div>

```

### CSS 实例

```css

/* 模态框 */

/* 遮罩 */

.modal .modal-backdrop {

/* 蒙板必须将弹层的后面全部盖住,意味着与容器大小一样 */

position: fixed;

top: 0;

left: 0;

right: 0;

bottom: 0;

background-color: rgb(0, 0, 0, 0.5);

}

/* 模态框主体 */

.modal .modal-body {

border: 1px solid #000;

padding: 1em;

min-width: 20em;

/* background-color: lightcyan; */

background: linear-gradient(to right, lightcyan, #fff);

/* 将一个块在别一个块中垂直水平居中 */

position: fixed;

left: 50%;

top: 50%;

-webkit-transform: translate(-50%, -50%);

transform: translate(-50%, -50%);

}

```

## fixed 原理

#####背景为灰色实现遮罩

` <div class="modal-backdrop"></div>`

```css

/* 蒙板必须将弹层的后面全部盖住,意味着与容器大小一样 */

position: fixed;

top: 0;

left: 0;

right: 0;

bottom: 0;

background-color: rgb(0, 0, 0, 0.5);

```

#####主体显示部份

`<div class="modal-body"> ... </div>`

```css

* 模态框主体 */ .modal .modal-body {

border: 1px solid #000;

padding: 1em;

min-width: 20em;

/* 背景色为渐变色 */

background: linear-gradient(to right, lightcyan, #fff);

/* 自动垂直水平居中 */

position: fixed;

left: 50%;

top: 50%;

-webkit-transform: translate(-50%, -50%);

transform: translate(-50%, -50%);

}

```

Tags:

最近发表
标签列表