CSS-元素居中显示的方法

作者: loushumei | 来源:发表于2019-07-23 15:07 被阅读0次

页面布局如下:

<div class="outer">
    <div class="inner">内部元素</div>
</div>

[元素已知高度和宽度]

方法一 :设置父元素为相对定位,给子元素设置绝对定位,left: 50%; top: 50%; margin-left: --元素宽度的一半px; margin-top: --元素高度的一半px;
.outer{
    width:500px;
    height: 400px;
    margin:0 auto;
    background: pink;
    position: relative;
}
.inner{
    width:100px;
    height: 100px;
    background: yellow;
    position: absolute;
    top:50%;
    left:50%;
    margin-top:-50px;
    margin-left:-50px;
}
方法二:设置父元素为相对定位,给子元素设置绝对定位,top: 0; right: 0; bottom: 0; left: 0; margin: auto;
.outer{
    width:500px;
    height: 400px;
    margin:0 auto;
    background: pink;
    position: relative;
}
.inner{
    width:100px;
    height: 100px;
    background: yellow;
    position: absolute;
    top:0;
    right:0;
    left:0;
    bottom:0;
    margin:auto;
}

元素未知宽度和高度

方法一:使用定位属性,设置父元素为相对定位,给子元素设置绝对定位,left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%);
  • Transform属性应用于元素的2D或3D转换。这个属性允许你将元素旋转,缩放,移动,倾斜等。
  • translate(x,y):元素在水平方向和垂直方向同时移动;
.outer{
    width:500px;
    height: 400px;
    margin:0 auto;
    background: pink;
    position: relative;
}
.inner{
    background: yellow;
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}
        
方案二:使用flex布局实现:设置父元素为flex定位,justify-content: center; align-items: center;
  • justify-content:属性应用在弹性容器上,把弹性项沿着弹性容器的主轴线(横轴)对齐。
  • align-items 属性应用在弹性容器上,设置或检索弹性盒子元素在侧轴(纵轴)方向上的对齐方式。
.outer{
    width:500px;
    height: 400px;
    margin:0 auto;
    background: pink;
    display: flex;
    justify-content: center;
    align-items: center;
}
.inner{
    background: yellow;
}
方案三:使用flex布局实现:设置父元素为flex定位,子元素设置margin: auto;
.outer{
    width:500px;
    height: 400px;
    margin:0 auto;
    background: pink;
    display: flex;
}
.inner{
    background: yellow;
    margin:auto;
}

相关文章

  • CSS-元素居中显示的方法

    页面布局如下: [元素已知高度和宽度] 方法一 :设置父元素为相对定位,给子元素设置绝对定位,left: 50%;...

  • CSS-居中

    CSS-居中 一. 水平居中 1. 行内元素水平居中 使用text-align属性,对行内元素定义居中 2. 块级...

  • CSS-居中

    CSS-居中 一. 水平居中 1. 行内元素水平居中 使用text-align属性,对行内元素定义居中 2. 块级...

  • 元素居中显示

    一、宽高未知 1. flex body就代表父元素,使用弹性盒模型就可以。 2.绝对定位和位移属性 div是要居中...

  • 网页布局各种居中问题的详解

    水平居中 行内元素水平居中 块级元素水平居中 多个块级元素水平居中 解决方法之一: 解决方法之二: 垂直居中 单行...

  • 元素的居中显示

    一、垂直居中显示的方法 1、对于单行文本元素, 设置元素的样式属性: 优点:适合所有浏览器,没有足够空间时,内容不...

  • css居中样式的总结

    1:文本居中显示text-align:center; 2:元素级别居中: 横向居中的子元素css样式设置posit...

  • css居中问题

    常用居中方法 居中在布局中很常见,我们假设DOM文档结构如下,子元素要在父元素中居中: 水平居中 子元素为行内元素...

  • CSS-元素显示模式

    在html中将html将所有标签分为两类:分别为容器级别和文本级别在CSS中CSS也将所有的标签分为两类:分为块级...

  • 多行文字垂直居中显示

    单行文字居中显示:line-height html: css: 多行文字居中显示: html: css: 给父元素...

网友评论

    本文标题:CSS-元素居中显示的方法

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