美文网首页
元素 居中 定位

元素 居中 定位

作者: LenHong | 来源:发表于2019-06-28 14:30 被阅读0次

纵向 margin 重叠
两个元素都有设置margin的情况下,两个元素之间的距离为那个margin较大的值

relative
设置top、bottom、left、right是相对于元素自身原来的位置而言

absolute

  • absolute 元素脱离了文档结构,会产生破坏性,导致父元素坍塌。
  • absolute 元素位置并没有发生变化,还是在它原本的位置
  • absolute 元素会悬浮在页面上方,会挡住下方的内容

水平居中

  1. inline 元素用text-align: center;
.container { text-align: center;}
  1. block 元素可使用margin: auto;
.item {
    width: 1000px;
    margin: auto;
}
  1. 绝对定位元素结合left和margin实现,但是必须知道宽度。
.container {
    position: relative;
    width: 500px;
}

.item {
    width: 300px;
    height: 100px;
    position: absolute;
    left: 50%;
    margin: -150px;
}

垂直居中

  1. inline 元素可设置line-height的值等于height值
.container {
  height: 50px;
  line-height: 50px;
}
  1. 绝对定位元素,可结合left和margin实现,但是必须知道尺寸
.container {
    position: relative;
    height: 200px;
}

.item {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -20px;
    margin-left: -40px;
}
  1. 也可以结合transform实现居中,不需要知道尺寸,兼容性不好
.container {
    position: relative;
    height: 200px;
}

.item {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: blue;
}
  1. 绝对定位结合margin: auto,不需要提前知道尺寸,兼容性好。
.container {
    position: relative;
    height: 300px;
}

.item {
    width: 100px;
    height: 50px;
    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin: auto;
}

flex布局

.container {
    display: flex;
    flex-direction: column-reverse| column | row | row-reverse;  设置元素是水平排列,还是垂直排列
    justify-content: flex-start | flex-end | center | space-between | space-around;  水平方向设置元素左对齐,右对齐,还是居中...
    align-items: flex-start | flex-end | center | baseline | stretch;  垂直方向设置元素上对齐,下对齐,还是居中...
}

.item {
    flex: 1;设置元素所占位置的大小
 }

相关文章

  • css 元素居中解决方案

    元素居中 居中div flex 定位+transform 定位

  • HTML 水平居中和垂直居中

    水平居中 文字居中 图片居中 绝对定位元素 居中 相对定位 负边距居中 垂直居中 文字设置line-height ...

  • 复习CSS

    居中对齐 inline元素 block元素 水平居中,知道宽度,左右margin为auto 定位元素 知道元素尺寸...

  • CSS居中问题总结

    1、居中元素宽高固定 绝对定位+margin 绝对定位+calc 2、被居中元素宽高不定 transform变换 ...

  • 元素 居中 定位

    纵向 margin 重叠两个元素都有设置margin的情况下,两个元素之间的距离为那个margin较大的值 rel...

  • 块元素水平垂直居中

    块元素水平垂直居中 使用flex布局将子元素水平垂直居中 使用position定位 或

  • 居中方法汇总

    1.行内元素居中 2.让块级元素在父级元素中水平居中 3.定位居中 4.基线对齐 5.单行垂直居中

  • css div垂直居中

    方案一:div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】, 方案二:div绝对定位水平垂...

  • html布局篇

    垂直居中 行内块级元素 position定位 flex布局 grid布局 水平居中 text-align 块级元素...

  • 居中问题

    css图片居中 1 tanslate居中 2 text-align属性水平居中 3 绝对定位元素居中 4 css3...

网友评论

      本文标题:元素 居中 定位

      本文链接:https://www.haomeiwen.com/subject/idwayqtx.html