当前位置:网站首页>块级元素上下左右居中的两个小技巧
块级元素上下左右居中的两个小技巧
2022-06-28 08:06:00 【庸懒】
块级元素的居中
之前写居中一般都是margin:atuto要么就是弹性盒子,不得不说弹性盒子确实好用。不过今天就记录一下另外两种的居中方式。
第一种
我们都知道元素居中有一种方式就是设置定位后left:50%然后transform:translateX(-50%),这种方法也是比较常用的一种。但是今天讲的居中方式和这个有点出入但是更简单。
<style>
.big{
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
margin: auto;
}
.small{
width: 100px;
height: 100px;
background-color: deeppink;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="big">
<div class="small"></div>
</div>
效果图如下:
可以看到我的大盒子的居中是使用的margin:auto,小盒子也是margin:auto,那为什么一个是左右居中另外一个就是上下左右都居中呢。
原因就是margin:auto居中的原理,因为margin:auto是根据元素的流来的,在上面的例子中大盒子是一个标准的块级元素,所以他的宽度默认是百分百的。
虽然大盒子看起来只有我设置的那么宽,但是他的流还是默认百分之百,所以我设置了margin:auto之后它就会居中。
那么小盒子也是同理,在定位之后我给了上下左右都为0,这样就会将小盒子的流拉伸至大盒子的大小,这个时候我给小盒子设置margin:auto就会让小盒子上下左右以大盒子为标准都居中。
第二种
第二种方式其实也用到了弹性盒子,但是比你设置主轴和副轴居中来的更为直接。
代码如下:
<style>
.big{
width: 300px;
height: 300px;
border: 1px solid red;
display: flex;
margin: auto;
}
.small{
width: 100px;
height: 100px;
background-color: deeppink;
margin: auto;
}
</style>
</head>
<body>
<div class="big">
<div class="small"></div>
</div>
这里的效果图和上面的一样我就不做演示了,我直接在这里说一下原因。
当元素设置了弹性盒子之后他的子元素自动变为块级元素,而该元素的副轴会被拉伸,所以呈现的效果和上面的一样。
边栏推荐
- Jacobian matrix J commonly used in slam
- B_QuRT_User_Guide(30)
- SLAM中常用的雅克比矩阵J
- 你了解TCP协议吗(一)?
- 三角变换公式
- Soft test -- software designer -- database design of afternoon questions
- Ambari (V) ---ambari integrated Azkaban (valid for personal test)
- 挖财注册开户靠谱吗?安全吗?
- Update pip to the latest version
- Trigonometric transformation formula
猜你喜欢

Kubernetes cluster command line tool kubectl

Cloud native: cloud computing technology is upgraded again to open an era of comprehensive cloud development

Section 5: zynq interrupt

软件测试与质量期末复习

MySQL tablespace parsing

Design of DSP image data stream

城联优品向英德捐赠抗洪救灾爱心物资

Disposition Flex

Software design of resistance test board

Introduction to Devops Basics
随机推荐
Airflow2.1.1 summary of the pits stepped on in actual combat!!
Cloud native: cloud computing technology is upgraded again to open an era of comprehensive cloud development
Trigonometric transformation formula
你了解TCP協議嗎(二)?
A single node obtains the lock lock of the order number
Connaissez - vous le protocole TCP (2)?
HJ prime factor
Unity 获取当前物体正前方,一定角度、距离的坐标点
sql分析(查询截取分析做sql优化)
How redis solves cache avalanche, breakdown and penetration problems
Upgrade HDP spark to spark 2.4.8 without upgrading ambari
HJ string sort
How to use redis to solve concurrency problems
协程、asyncio、异步编程
HJ base conversion
NLP sequence can completely simulate human brain intelligence
HJ进制转换
你了解TCP协议吗(一)?
HJ字符串排序
Host is not allowed to connect to this MySQL server