当前位置:网站首页 > 学习记录 > 正文

css+div上下左右自适应居中

评论:1 发布时间: 2020-04-17 浏览: 2773

1.登录框上下左右自适应居中

原理就是用position:absolute,然后用left:50%,top:50%,现在登录表单左侧直角是在页面的中间了,

但登录框本身还有宽度和高度,所以我们再用margin-left:-登录框宽度,margin-top:-登录框高度,就可以让登录框显示在页面的正中间了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>登录框自适应居中</title>
    <style>
    #LoginContainer {
        position: absolute;
        width:400px;
        height:200px;
        left:50%;
        top:50%;
        margin-left:-200px;
        margin-top:-100px;
        border:1px solid #ccc;
    }
    </style>
</head>
<body>
    <div id="LoginContainer">
    这是登录框
    </div>
</body>
</html>

2.左右布局,左侧固定宽度,右侧自适应宽度

原理就是左侧div固定宽度+float,然后右侧的div设置左间隔左侧div宽度的距离就可以了(margin-left:左侧div的宽度)

复制代码
<style type="text/css">
    html, body { padding: 0px; margin: 0px; height: 100%; overflow: hidden; }
    .container { height: 100%; border: 1px solid #ccc; min-width: 600px; }
        .container .west { border-right: 1px solid #ccc; height: 100%; width: 200px; float: left; }
        .container .content { height: 100%; margin-left: 200px; }</style><div class="container">
    <div class="west">west</div>
    <div class="content">content</div></div>
复制代码

 3.利用translate(-50%, -50%)居中(红色为关键部分)

  position: fixed;
  min-width: 100px;
  color: #fff;
  border-radius: 2px;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 10px 5px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;


TAGS:

已有1位网友发表了看法:

  • wys

    wys  评论于 [2020-04-18 07:24:15]  回复

    好久没学了。刚玩网站时还买了本dreamweaver。

欢迎 发表评论: