如何在 CSS 中居中放置子元素,即使它比父元素大? [英] How to center a child element in CSS, even if it is larger than the parent?

查看:63
本文介绍了如何在 CSS 中居中放置子元素,即使它比父元素大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 css 类,以便 div 可以放置在其父项的中心.我使用的代码是:

.center {位置:绝对;保证金:自动;底部:0px;左:0px;顶部:0px;右:0px;}

如果父元素大于子元素或具有相同的大小,它会起作用:https://jsfiddle.net/cy8dn1km/

但是如果孩子更大,那么它的中心就不会定位在它的父母的中心.相反,它们的左边框将在同一位置,并且子元素将仅向右扩展:

https://jsfiddle.net/797L7nce/

水平居中有问题.

如何仅使用 CSS(不使用 CSS 2D/3D 转换)而不添加新的容器元素来修复它?

解决方案

这是一个不使用 CSS 2D/3D 转换的解决方案.您可以在父元素和 display: table 上使用 display: flexflex-direction: column(这是重要)子元素上的代码>.

body,html {宽度:100%;高度:100%;边距:0;}身体 {显示:弹性;对齐项目:居中;对齐内容:居中;背景:绿色;}.center.d1 {显示:弹性;对齐项目:居中;对齐内容:居中;弹性方向:列;}.d1{背景:黄色;宽度:50px;高度:50px;}.d2 {背景:红色;不透明度:0.7;宽度:250px;高度:250px;显示:表;}

<div class="centerd2"></div>

I would like to create a css class so a div can be placed in the center of its parent. The code I am using is:

.centered {
    position: absolute;
    margin: auto;

    bottom: 0px;
    left: 0px;
    top: 0px;
    right: 0px;
}

It works if the parent is larger than the child element, or has the same size: https://jsfiddle.net/cy8dn1km/

But if the child is larger, then its center is not positioned at the center of its parent. Instead their left borders will be at the same place, and the child element will be extended only to right:

https://jsfiddle.net/797L7nce/

Something is wrong with the horizontal centering.

How is it possible to fix it using CSS only (without using CSS 2D/3D transformations), without adding new container elements?

解决方案

Here is a solution without using CSS 2D/3D transformations. You can use display: flex with flex-direction: column (this is important) on parent element and display: table on child element.

body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: green;
}
.centered.d1 {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.d1 {
  background: yellow;
  width: 50px;
  height: 50px;
}
.d2 {
  background: red;
  opacity: 0.7;
  width: 250px;
  height: 250px;
  display: table;
}

<div class="centered d1">
  <div class="centered d2"></div>
</div>

这篇关于如何在 CSS 中居中放置子元素,即使它比父元素大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆