CSS-元素居中显示的方法

页面布局如下:

<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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,692评论 1 92
  • CSS 是什么 css(Cascading Style Sheets),层叠样式表,选择器{属性:值;属性:值}h...
    崔敏嫣阅读 5,360评论 0 5
  • 一、CSS入门 1、css选择器 选择器的作用是“用于确定(选定)要进行样式设定的标签(元素)”。 有若干种形式的...
    宠辱不惊丶岁月静好阅读 5,555评论 0 6
  • HTML 5 HTML5概述 因特网上的信息是以网页的形式展示给用户的,因此网页是网络信息传递的载体。网页文件是用...
    阿啊阿吖丁阅读 9,945评论 0 0
  • 选择qi:是表达式 标签选择器 类选择器 属性选择器 继承属性: color,font,text-align,li...
    love2013阅读 6,861评论 0 11

友情链接更多精彩内容