花了两三天大概看完html和css基本用法,但到自己布局的时候还是很懵不知道从哪里入手啊,就找了个简单的任务(ife2015 spring)试一下。
之前不涉及到布局的跳过,从涉及到position和float的开始,这一块看的有点晕,结合下面的例子搞懂了。
例:用两种方法来实现一个背景色为红色、宽度为960px的<DIV>在浏览器中居中。我用了三种方法。代码如下:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="task0001_css.css">
<title>task0001</title>
<style type="text/css">
a:link {text-decoration: none;}
a:visited {color: black;}
a.hover{text-decoration:underline;}
a:active {color:yellow;}
</style>
</head>
<body>
<h1> MyGitbubAccountName:SMQ</h1>
<ul>
<li>
<a href="https://github.com/baidu-ife/ife/tree/master/2015_spring/task/task0001"><span>homepage</a>
</li>
<li>
<a href="http://www.douban.com" target="_blank"><span>douban</a>
</ul>
<h2>这是二级标题</h2>
<p>这里有一个文字段落这里有一个文字段落
这里有一个文字段落这里有一个文字段落
</p>
<div class="box1">div1</div><br>
<div class="centerbox">
<div class="box2">div2</div>
</div><br>
<div class="box3">div3</div>
</body>
</html>h1 {color: blue}
h2 {font-size: 14px}
p {
font-size: 20px;
color: #FFFF00;
background-color: gray;
text-indent: 50px;
text-decoration: blink underline;
text-transform: capitalize;
text-align:left;
word-spacing: 3px;
}
.box1{ background-color:red;
width: 960px;
position: relative; /*如果用absolute 换行符br就没用了*/
left:50%;
margin-left: -480px; /*画图看为什么可以这样,总结*/
}
.centerbox{
width: 960px;
position: relative;
left: 50%;
}
.box2 {
background-color:blue;
position: relative;
left: -50%;
}
.box3{
background-color:blue;
width: 960px;
margin: auto;
} box1 box2 box3 分别对应三种实现方法。注意属性不能用数字开头,一开始我直接命名为123无效。
先说box1:使用position:relative对div元素相对定位,是相对于他本来的位置,即浏览器界面的最左端来说的,然后用left:50%将其左移50%,是相对整个浏览器界面的50%,然后再用margin-left: -480px把div移到中间位置。
box2:先设定一个往左移了50%的父元素,然后在子元素中使用left:-50%移到中间。
box3:使用margin:auto让浏览器自动设置外边距。
例:用两种不同的方法来实现一个两列布局,其中左侧部分宽度固定、右侧部分宽度随浏览器宽度的变化而自适应变化
一种用浮动,一种用绝对定位实现。
/*用浮动实现:*/.c1 {
float:left;
background-color:yellow;
width: 200px;
height: 300px;
}
.c2 {
background-color:blue;
width: 100%;
height: 300px;
}
.c3{
clear:both;
background-color:green;
height: 50px;
}/*用绝对定位实现*/
#c{
position:relative;
}
.c1{
position:absolute;
background:yellow;
width: 200px;
height:300px;
top:0;
left:0;
}
.c2{
background:blue;
margin-left: 200px; /*两列布局只需要一个absolute??
没有position时不能用width=100%会出错*/
height:300px;
}
.c3{
position: absolute;
width:100%;
background: green;
top: 300px;
height:50px;
}