最近一个刚刚毕业的朋友说,他面试时候,遇到最频繁的css问题就是垂直居中,这里给出几种垂直居中方式!...

本文介绍了三种不同的CSS技术来实现网页元素的水平垂直居中:使用绝对定位和负边距、利用table-cell特性以及通过transform属性。这些方法适用于不同的场景需求。

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

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	
</head>
<style>
	html {
    background: #f9f9f9;
    overflow-y: scroll;
}
body{
	font-size: 14px;
	font-family: "微软雅黑";
	padding: 0;
	margin:0 auto;
}

#child {
	position:absolute;
	top:50%;
	left: 50%;
	width: 100px;
	height:20px;
	margin:-10px 0px 0px -50px; /* negative half of the height */
    background-color: #ddd;
    text-align: center;
    line-height:20px;
}
</style>
<body>
<div id="parent">
		<div id="child">Content here</div>
</div>
</body>
</html>

  

<!DOCTYPE html>
    <head>
        <title>center</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style>    
            .root {
                width:100%;
                height:100%;
                display:table;
                background-color: rgba(0,0,0,0.5);
                position: fixed;
            }
            .parent {
                display:table-cell;
                vertical-align:middle;
            } 
            .child {
                width:50px;
                height:50px;
                background:#22B14C;
                margin:0 auto;
            }            
        </style>
    </head>
    <body>
        <div class="root">
            <div class="parent">
                 <div class="child"></div>
            </div>
        </div>
    </body>
</html>

  

<!DOCTYPE html>
    <head>
        <title>center</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style> 
        body{
            margin:0;
            padding: 0;

        }   
            .parent {
                width:100%;
                height:100%;
                border:1px solid black;
                position: fixed;
                background-color: rgba(0,0,0,0.5);
           
            }
            .child {
                position:absolute;
                width:50px;
                height:50px;
                top:50%;
                left:50%;
       
                -webkit-transform: translate(-50%,-50%);
                    -ms-transform: translate(-50%,-50%);
                   -o-transform: translate(-50%,-50%);
                   transform: translate(-50%,-50%);
                background:#22B14C;
            }         
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="child">
                 
            </div>
            
        </div>
    </body>
</html>

  

 

转载于:https://www.cnblogs.com/null11/p/5429634.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值