day1-简单的元素居中方式介绍

152 阅读1分钟

元素居中

在盒子里,元素居中分为行内元素居中块级元素居中,居中方式又分为水平居中垂直方向居中

1.行内元素水平居中text-align: center;

<head>
    <style>
        .container {
            height: 100px;
            background-color: red;
        }
        .aaa {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <p class="aaa">AAAAAA</p>
    <div>
</body>

微信截图_20221020005823.png

2.行内元素垂直居中line-height: (父元素的height);

在上述代码的基础上给子元素".aaa"添加line-height样式:

    <style>
        .aaa {
            text-align: center;
            line-height: 100px;
        }
    </style>

父元素高度是100px,子元素的line-height值也设置为100px便可以在父元素垂直居中 微信截图_20221020010336.png

3.块级元素水平居中margin: 0 auto;

<style>
	.father {
		width: 100px;
		height: 100px;
		background-color: red;
	}

	.son {
		width: 40px;
		height: 40px;
		background-color: greenyellow;
		margin: 0 auto;
	}
</style>

微信截图_20221020013018.png

此篇分享比较简单,浅显入门。后续会持续更新