CSS:如何直接将div元素居中居中? [英] css: how to center box div element directly in center?

查看:41
本文介绍了CSS:如何直接将div元素居中居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用top:50%和left:50%

when i use top:50% and left:50%

该框不直接位于中间.当然,当盒子很小时,它似乎居中.但是当盒子有点大时,看起来好像没有居中.

the box is not directly in center. of course when the box is very small, it appears to be centered. but when box is a bit big, it looks as if it's not centered.

我该如何解决?

推荐答案

top left 对应于框的左上角.您正在尝试做的是让它们与中心相对应.因此,如果将 margin-top margin-left 分别设置为高度和宽度的一半的负数,则会得到一个居中的框.

top and left correspond to the top-left corner of your box. What you're trying to do is have them correspond to the center. So if you set margin-top and margin-left to negative of one-half the height and width respectively, you'll get a centered box.

300x200框的示例:

Example for a 300x200 box:

width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -100px;

这篇关于CSS:如何直接将div元素居中居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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