1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > div在body中水平垂直居中

div在body中水平垂直居中

时间:2024-04-22 21:41:04

相关推荐

div在body中水平垂直居中

<!DOCTYPEhtml>

<htmllang="en">

<head>

<metacharset="UTF-8">

<metaname="viewport"content="width=device-width,initial-scale=1.0">

<title>水平垂直居中与body</title>

<linkrel="stylesheet"type="text/css"href="./css/index2.css">

</head>

<body>

<divclass="absolute0marginauto">

绝对定位上下左右都是0px,margin使用auto

</div>

<divclass="flexcenterparent">

<divclass="flexcentersub">

使用css3的flex模式justify-content:centeraligin-items:center模式居中,但这个有点不适合在body中垂直水平居中,因为如果body都设置这种模式,那它里面的元素都水平垂直剧终了

</div>

</div>

<divclass="marginwidhthalf">

使用绝对定位left50%top50%然后margin-left:div宽度高度一半margin-top:div高度一半,

这种需要知道本身的widthheight

</div>

<divclass="absolutetransform">

使用绝对定位然后使用transform(-50%,-50%),进行移动,这种方法,不需要知道宽高,

我不需要知道宽高

</div>

</body>

</html>

--css

*{

margin:0px;

padding:0px;

}

html,body{

width:100%;

height:100%;

}

.absolute0marginauto{

width:100px;

height:100px;

position:absolute;

top:0px;

bottom:0px;

left:0px;

right:0px;

margin:auto;

background:brown;

}

.flexcenterparent{

width:300px;

height:300px;

display:flex;

justify-content:center;

align-items:center;

border:2pxsolidred;

}

.flexcentersub{

width:200px;

height:200px;

border:2pxsolidblue;

}

.marginwidhthalf{

width:200px;

height:200px;

border:2pxsolidviolet;

position:absolute;

left:50%;

top:50%;

margin-left:-100px;

margin-top:-100px;

}

.absolutetransform{

border:4pxsoliddarkmagenta;

color:darkorange;

position:absolute;

top:50%;/*这个的50%是父元素的50%,二translate50%是div本身的50%*/

left:50%;

transform:translate(-50%,-50%);

}

顺便说下 文在在div中水平居中,使用 text-algin:center 垂直居中line-height:divheight

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。