css怎么让一个段落居中,css让一个div绝对居中

css让一个div绝对居中

方法1

/* css */

html,body{

height: 100%;

}

body{

margin: 0;

background-color: bisque;

position: relative;

}

div{

background-color: aqua;

width: 80px;

height: 200px;

position: absolute;

left: 50%;

top: 50%;

margin-left: -40px;

margin-top: -100px;

}

该方法利用css中父相子绝,让div根据body来进行定位(不加 position: relative;相对定位的话,默认也会相对body来进行定位). left: 50%; top: 50%;会使该div左上角在页面中间.加上 margin-left: -40px; margin-top: -100px;就形成了绝对居中. 该方法适用于宽高都确定的情况下

方法2

/* css */

html,

body {

height: 100%;

}

body {

margin: 0;

background-color: bisque;

position: relative;

}

div {

background-color: aqua;

width: 80px;

height: 200px;

position: absolute;

left: 0;

top: 0;

bottom: 0;

right: 0;

margin: auto;

}

该方法是将元素完全脱离文档流使用margin: auto;将div上下,左右都完全居中;

方法3

/* css */

html,

body {

height: 100%;

}

body {

margin: 0;

background-color: bisque;

display: flex;

justify-content: center;

align-items: center;

}

div {

background-color: aqua;

width: 80px;

height: 200px;

}

该方法利用的css3的弹性盒子使横轴以及纵轴都达到了居中的效果 IE10及其以下版本都不兼容

方法4

/* css */

html,

body {

height: 100%;

}

body {

margin: 0;

background-color: bisque;

position: relative;

}

div {

background-color: aqua;

width: 80px;

height: 200px;

position: absolute;

left: 50%;

top: 50%;

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

}

该方法利用的css3中 transform属性中translate(-50%, -50%)进行的一个2D的转换,达到了居中的效果

IE10及其以下版本都不兼容

方法5

/* css */

body {

margin: 0;

background-color: bisque;

width: 2000px;

height: 1000px;

display: table-cell;

text-align: center;

vertical-align: middle;

}

div {

background-color: aqua;

width: 80px;

height: 200px;

display: inline-block;

}

该方法利用文本居中,(不常用).而且必须要有绝对的宽和高百分比的宽高也不可以

方法6

// 基本样式的设定

// box代表div

box.style.width = '80px'

box.style.height = '200px'

box.style.background = ' aqua'

document.body.style.position = 'relative'

document.body.style.background = 'bisque'

let htm = document.documentElement

let htmWidth = htm.clientWidth

let htmHeight = htm.clientHeight

let boxW = box.clientWidth

let boxH = box.clientHeight

box.style.position = 'absolute'

box.style.left = (htmWidth-boxW)/2 +'px'

box.style.top =( htmHeight-boxH)/2 +'px'

该方法也是用的绝对定位,利用js算出left,和top的精确值,绝对定位到页面的中间

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值