子元素在父元素中定位:居中显示

水平居中(margin:0 auto;)

关于这个,大家应该是最不陌生的,不管是在培训班还是自己自学的话 。这个应该是老师讲的第一个方法了(水平方向上),但是其有一个前提,就是被包裹的元素不能有浮动的属性。否则的话这个属性就会失效。具体如下图代码:

<style>
        body{margin: 0;}
        .box{
            width: 400px;
            height: 400px;
            border:1px solid red;
        }
        item{
            margin:0 auto;
            width: 100px;
            height: 100x;
            background: green;
        }
</style>
<body>
    <div class="box">
        <div class="item"></div>
     </div>
</body>

image.png

水平垂直居中: 子元素相对于父元素绝对定位,并且margin值位auto

* {
				margin: 0;
				padding: 0;
			}

			.box {
				position: relative;
				margin: 0 auto;
				height: 400px;
				width: 400px;
				background-color: #00FF00;
			}

			.children {
				position: absolute;
				right: 0px;
				top: 0px;
				bottom: 0px;
				margin: auto 0;
				
				height: 100px;
				width: 100px;
				background-color: #FF00FF;
			}
		<div class="box">
			<div class="children"></div>
		</div>

image.png

水平居中(text-align:center;)

这个属性在没有浮动的情况下,我们可以将其转换为inline/inline-block,然后其父元素加上text-align:center;属性就可以将其居中

<style>
        body{margin: 0;}
        .box{
            width: 400px;
            height: 400px;
            border:1px solid red;
            text-align:center;
        }
        item{
            display:inline/inline-block;
            width: 100px;
            height: 100x;
            background: green;
        }
</style>
<body>
    <div class="box">
        <div class="item"></div>
     </div>
</body>

image.png

flex布局

		 * {
				margin: 0;
				padding: 0;
			}

			.box {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				
				height: 400px;
				width: 400px;
				background-color: #00FF00;
			}

			.children {
				height: 100px;
				width: 100px;
				background-color: #FF00FF;
			}

		<div class="box">
			<div class="children"></div>
		</div>

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值