300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > HTML水平垂直居中的四种方式

HTML水平垂直居中的四种方式

时间:2023-10-02 12:49:49

相关推荐

HTML水平垂直居中的四种方式

第一种方式是使用margin进行移动

水平居中 margin:0 auto;

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>水平垂直居中</title><style>/* 设置父容器样式和高度 */.container{width: 400px;height: 400px;border: 5px solid black;}/* 子元素的样式 */.container>div{width: 200px;height: 200px;background-color: blue;/* 水平居中 */margin: 0 auto;}</style></head><body><!-- 父容器 --><div class="container"><!-- 子元素 --><div></div></div></body></html>

要设置垂直居中的话,就要根据父元素的高度和子元素的高度进行计算,也就是父元素的高度的一半再减去子元素的高度的一半

/* 子元素的样式 */.container>div{width: 200px;height: 200px;background-color: blue;/* 水平垂直居中 */margin: 100px auto;}

水平垂直居中

第二种方式就是使用flex布局,让父容器设置为display:flex;设置主轴方向justify-content:center

交叉轴为align-items:center

<style>/* 设置父容器样式和高度 */.container{width: 400px;height: 400px;border: 5px solid black;/* 父元素开启flex布局 */display: flex;/* 主轴方向上居中 */justify-content: center;/* 交叉轴方向上居中 */align-items: center;}/* 子元素的样式 */.container>div{width: 200px;height: 200px;background-color: blue;}</style>

第三种方式使用绝对定位和相对,给父容器设置为相对相位position:relative;

水平居中:先子元素设置绝对定位position:absolute; 设置绝对定位元素的left:50%; 然后再设置绝对定位元素的 margin-left: -元素宽度的一半px; margin-left:-100px

垂直居中:就要根据父元素的高度和子元素的高度进行计算,也就是父元素的高度的一半再减去子元素的高度的一半

<style>/* 设置父容器样式和高度 */.container{width: 400px;height: 400px;border: 5px solid black;/* 父容器相对定位 */position: relative;}/* 子元素的样式 */.container>div{/* 子元素绝对定位 */position: absolute;width: 200px;height: 200px;background-color: blue;/* 设置绝对定位元素的left:50%; */left: 50%;/* 设置子元素左外边距 */margin-left: -100px;/* 再根据父容器和子元素的高度算出垂直居中的高度 */margin-top: 100px;}</style>

还有一种水平垂直居中的方式也是使用绝对定位和相对定位,也是给父容器设置相对定位,子元素设置绝对定位,然后让绝对定位的元素的上下左右都为0,再给个margin:auto就行了

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>水平垂直居中</title><style>/* 设置父容器样式和高度 */.container{width: 400px;height: 400px;border: 5px solid black;/* 父容器相对定位 */position: relative;}/* 子元素的样式 */.container>div{/* 子元素绝对定位 */position: absolute;width: 200px;height: 200px;background-color: blue;margin: auto;left: 0;top: 0;bottom: 0;right: 0;}</style></head><body><!-- 父容器 --><div class="container"><!-- 子元素 --><div></div></div></body></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。