一个div在另一个div中水平居中_div里面的div水平居中

(1) 2024-09-16 09:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
一个div在另一个div中水平居中_div里面的div水平居中,希望能够帮助你!!!。

小编在做练习时遇到了一个问题:如何使一个div在另一个div里面水平和垂直两个方向全部居中。之前一般的情况都是一个div在另一个div里面水平居中,直接使用margin:0 auto;即可解决。这次的情况第一次遇到,网上找了一些方法,亲测有效,总结如下,将其放入一个页面内了。

一个div在另一个div中水平居中_div里面的div水平居中_https://bianchenghao6.com/blog__第1张

HTML部分:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

</head>

<body>

<div class="parent1">

<div class="child1">方法一</div>

</div>

<div class="parent2">

<div class="child2">方法二</div>

</div>

<div class="parent3">

<div class="child3">方法三</div>

</div>

<div class="parent4">

<div class="child4">方法四</div>

</div>

</body>

</html>

一个div在另一个div中水平居中_div里面的div水平居中_https://bianchenghao6.com/blog__第2张CSS部分:

<style>

*{margin: 0;padding: 0;}

/*方法一*/

.parent1{

width: 500px;height: 200px;

border: 4px solid #FF4500;

position: relative;

margin-top: 20px;margin-bottom: 20px;

}

.child1{

width: 200px;height: 150px;

margin: auto;position: absolute;

top: 0;right: 0;bottom: 0;left: 0;

background-color: #008B8B;

line-height: 150px;

text-align: center;

color: white;

}

/*方法二*/

.parent2{

width: 500px;height: 200px;

border: 4px solid #008B8B;

display: table-cell;

vertical-align: middle;

text-align: center;}

.child2{

width: 200px;height: 150px;

display: inline-block;

background-color: #008B8B;

line-height: 150px;color: white;

}

/*方法三*/

.parent3{

width: 500px;height: 200px;

border: 4px solid #008B8B;

margin-top: 20px;

display: flex;

justify-content: center;

align-items: center;

}

.child3{

width: 200px;height: 150px;

background-color: #008B8B;

line-height: 150px;

text-align: center;

color: white;

}

/*方法四 */

.parent4{

width: 500px;height: 200px;

border: 4px solid #FF4500;

position: relative;

margin-top: 20px;

}

.child4{

width: 200px;height: 150px;

background-color: #008B8B;

position: absolute;

top: 50%;left: 50%;

margin-left: -100px;

margin-top: -75px;

line-height: 150px;

text-align: center;

color: white;

}

</style>

最后效果图如下:

一个div在另一个div中水平居中_div里面的div水平居中_https://bianchenghao6.com/blog__第3张

以上就是几种简单的居中方法,本文纯属练习,如有错误欢迎各位指出。

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复