html css 如何让未知大小的div居中

2024-10-15 11:37:37

让已知大小的div居中很容易,可以写死top和left的长度或者写死内外边距等。但我建议即使是已知大小的div,也使用接下来介绍的这2种方法来居中,这样可以让你的代码具有更强的应对变化的能力,并且节省调整数值的时间。。

编写基本结构

1、可以使用在线编辑前端代码的网站如jsrun来尝试以下代码

2、编写一个最简短的2个div嵌套的结构<div class="outer"> <div class="inner center"> </div></div>

html css 如何让未知大小的div居中html css 如何让未知大小的div居中

2、使用transform居中代码和很简短,很好记.center { left: 50%; top: 50%; transform: translate(-50%, -50%);}

html css 如何让未知大小的div居中

3、可以单独控制上下居中.center { top: 50%; transform: translate(0, -50%);}

html css 如何让未知大小的div居中

margin: auto

1、使用margin:auto控制居中和transform达到的效果一样,代码要多2行。.center { left: 0; top: 0; right: 0; bottom: 0; margin: auto;}

html css 如何让未知大小的div居中html css 如何让未知大小的div居中
猜你喜欢