必须知道的css水平、垂直居中

简介:   在网页制作中,有很多种水平、垂直居中方法,本文就归纳如下几种:  水平居中  1.不建议用了。  2. text-align:center 在父容器里水平居中 inline 文字,或 inline 元素  3.margin:0 auto;  4.用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。

  在网页制作中,有很多种水平、垂直居中方法,本文就归纳如下几种:

  水平居中

  1.

不建议用了。
  2. text-align:center 在父容器里水平居中 inline 文字,或 inline 元素

  3.margin:0 auto;

  4.用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。

  

Hello World
  样式

  #ex3_container{

  width:200px;

  height:200px;

  background-color:yellow;

  position:relative;

  }

  #ex3_content{

  left:50%; top:50%;

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

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

  background-color:gray; color:white; position:absolute;

  }

  这个技巧相当嚣张,适用于没固定大小的内容,min-width,max-height,overflow:scroll等。

  5.绝对定位居中

  父容器元素:position: relative

  .Absolute-Center {

  width: 50%;

  height: 50%;

  overflow: auto;

  margin: auto;

  position: absolute;

  top: 0; left: 0; bottom: 0; right: 0;

  }

  注意:高度必须定义,建议加 overflow: auto,防止内容溢出。

  6.视口居中

  内容元素:position: fixed,z-index: 999,记住父容器元素 position: relative

  .Absolute-Center.is-Fixed {

  width: 50%;

  height: 50%;

  overflow: auto;

  margin: auto;

  position: fixed;

  top: 0; left: 0; bottom: 0; right: 0;

  z-index: 999;

  }

  垂直居中

  1.

  

  

  

Content goes here
  

  

  样式

  .wrapper{display:table;}

  cell{display:table;

  vertical-align:middle;

  }

  2.这个方法使用绝对定位div,把它的top设置为50%,top margin 设置为负的content高度,这意味着对象必须在css种指定用域名转让固定的高度

  因为有固定高度,或许你想给content指定overflow:auto,这样如果content太多的话,就会出现滚动条,以免content溢出

  

content goes here
  样式

  .content {

  position:absolute;

  top:50%;height:240px;

  margin-top:-120px;/ negative half of the height /

  }

  3.content元素外插入一个div

  

  

content here
  样式

  .floater{

  float:left;

  height:50%;

  margin-bottom:-120px;

  }

  .content{

  clear:both;

  height:240px;

  position:relative;

  }

  4.会计元素垂直居中是很简单的

  

content here
  样式

  .content{

  position:absolute;

  top:0;

  bottom:0;

  left:0;

  right:0;

  margin:auto;

  height:240px;

  widthZ:70%;

  }

  5.line-height

  

content here
  样式

  .content{

  height:100px;

  line-height:100px;

  }

目录
相关文章
|
1月前
|
前端开发
CSS水平居中与垂直居中的方法
CSS水平居中与垂直居中的方法
|
2月前
|
前端开发 容器
css 中可以让文字在垂直和水平方向上重叠的两个属性是什么?
css 中可以让文字在垂直和水平方向上重叠的两个属性是什么?
|
2月前
|
人工智能 前端开发 开发者
Baidu千帆大模型赋能——CSS控制DIV垂直水平居中——送给大一的孩子们,学会用AI思维来帮助你解决问题
Baidu千帆大模型赋能——CSS控制DIV垂直水平居中——送给大一的孩子们,学会用AI思维来帮助你解决问题
26 1
|
3月前
|
前端开发 Java C++
面试官:用 CSS 实现一个元素的水平垂直居中,写出你能想到的所有答案
面试官:用 CSS 实现一个元素的水平垂直居中,写出你能想到的所有答案
|
3月前
|
前端开发
css水平居中的5种几种方式
css水平居中的5种几种方式
|
9月前
|
前端开发
DIV+CSS文字与图片上下垂直居中-div css居中
DIV+CSS文字与图片上下垂直居中-div css居中
43 0
|
4月前
|
前端开发 容器
css中元素水平居中的方式
css中元素水平居中的方式
44 0
|
4月前
|
前端开发
CSS 垂直居中
CSS 垂直居中
|
4月前
|
前端开发
CSS div 水平排列
CSS div 水平排列
|
5月前
|
前端开发
css设置div水平居中
css设置div水平居中