實現絕對定位元素水平垂直居中的兩種方法

2022-07-26 20:36:15 字數 635 閱讀 2721

平時,用的方法即第一種方法是設定left,top值均為50%,同時margin-left設定為絕對定位元素width的一半取負,margin-top設為其height的一半取負。

例如,絕對定位元素的width:100px;height:100px;

**如下:

position:absolute;

left:50%;

top:50%;

margin-left:-50px;

margin-top:-50px;

這是比較常用的乙個方法,今天介紹乙個巧妙的方法,是利用了絕對定位元素的自動伸縮的特性實現的。

**如下:

position:absolute;

left: 0;

right: 0;

top: 0;

bottom: 0;

margin:auto;

上面就是第二種方法:設定margin:auto;設定left和right的值相等,top和bottom的值相等,

注意:left和right的值不能超過其相對元素width減去它自身width的一半,否則絕對定位元素會優先取left值進行定位(前提是文件流是從左向右),但是top和bottom的值卻沒有這個限制。

絕對定位元素的水平垂直居中

1.負邊距實現絕對定位元素的居中 1 head 2 style type text css 3.container 9.box 19style 20head 21 body 22 div class container 23 div class box 24div 25div 26body 優點 相...

css 絕對定位元素水平垂直居中

position absolute top 0 left 0 right 0 bottom 0 margin auto 設定margin auto 設定left和right的值相等,top和bottom的值相等,注意 left和right的值不能超過其相對元素width減去它自身width的一半,否...

絕對定位元素的水平垂直居中的方法

缺點 需要提前知道元素的寬度和高度。doctype html en utf 8 document title box style head 相對定位元素 box 絕對定位元素 div div body html 當元素的尺寸不固定時,都可以居中。不過ie8以上才相容這種寫法,移動端可忽略。docty...