css居中的总结

本文详细介绍了多种让网页元素居中的CSS技术,包括text-align、line-height、margin: 0 auto、flexbox布局以及绝对定位结合负margin等方法。这些技巧适用于行内元素、行内块元素和块级元素的居中对齐,为网页设计提供了灵活的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

text-align行内元素或行内块元素的居中

<style>
	.parent{
	    width: 200px;
	    height: 200px;
		text-align: center;
	    background: red;
	}
	.children{
		/*
			行内块也具有行内元素的特性
			因此使用text-align也有效果
		*/
	    display: inline-block;
	    width: 100px;
	    height: 100px;
	    background: lightblue;
	}
</style>
<div class="parent">
	<div class="children"></div>
</div>

效果:
在这里插入图片描述
line-height文字垂直居中

<style>
	.parent{
	    width: 200px;
	    height: 200px;
		line-height: 200px;
	    background: lightblue;
	}
</style>
<div class="parent">
	文字文字
</div>

在这里插入图片描述

margin: 0 auto 块级元素的居中

<style>
	.parent{
	    width: 200px;
	    height: 200px;
		text-align: center;
	    background: red;
	}
	.children{
		/*
			平方包含块可用空间
		*/
		margint:0 auto;
	    width: 100px;
	    height: 100px;
	    background: lightblue;
	}
</style>
<div class="parent">
	<div class="children"></div>
</div>

在这里插入图片描述
flex居中

<style>
	.parent{
		display: flex;
		justify-content: center;
		align-items: center;
	    width: 200px;
	    height: 200px;
	    background: red;
	}
	.children{
	    width: 100px;
	    height: 100px;
	    background: lightblue;
	}
</style>
<div class="parent">
	<div class="children"></div>
</div>

效果:
在这里插入图片描述

绝对定位居中:

<style>
	.parent{
	    position: relative;
	    width: 200px;
	    height: 200px;
	    background: red;
	}
	.children{
	    position: absolute;
	    left: 0px;
	    right: 0px;
	    top: 0px;
	    bottom: 0px;
	    margin: auto;
	    width: 100px;
	    height: 100px;
	    background: lightblue;
	}
</style>
<div class="parent">
	<div class="children"></div>
</div>

在这里插入图片描述

绝对定位+负margin

 <style>
	.parent{
     position: relative;
     width: 200px;
     height: 200px;
     background: red;
	}
	.children{
     position: absolute;
     top: 50%;
     left: 50%;
     width: 100px;
     height: 100px;
     margin: -50px;
     background: lightblue;
   }
</style>
<div class="parent">
	<div class="children"></div>
</div>

在这里插入图片描述

table-cell居中

 <style>
	.parent{
	     display: table-cell;
	     text-align: center;
	     vertical-align: middle;
	     text-align: center;
	     width: 200px;
	     height: 200px;
	     background: red;
	}
	.children{
	     display: inline-block;
	     width: 100px;
	     height: 100px;
	     background: lightblue;
	}
</style>
<div class="parent">
	<div class="children"></div>
</div>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值