CSS如何给一个绝对定位的元素设定自适应宽度

html-css019

CSS如何给一个绝对定位的元素设定自适应宽度,第1张

像div这样的块元素在默认定位下你是不用担心它在页面上自适应宽度的问题的,但是一旦它使用了绝对定位,它就不会乖乖的填满你需要的宽度了。

那么,这个时候我们应该怎么办呢?

答案是用left和right来处理。

我们只需要给DIV设定样式

left:

0

right:

0

你的div就会像你需要的那样实现自适应了。

一、float实现

html结构:

[html] view plain copy

<div class="left"></div>

<div class="right"></div>

<div class="center"></div>

css:

[css] view plain copy

.left,.right{

width: 200px

height: 300px

background-color: red

}

.left{

float: left

}

.right{

float: right

}

.center{

margin: 0 210px

height: 300px

background-color: blue

}

这种实现受外界影响小,但是对html结构有要求(center必须放在最后,left与right则无所谓),当界面缩小到一定程度时,right会被挤到下一行

二、position实现

html结构:

[html] view plain copy

<div class="left"></div>

<div class="right"></div>

<div class="center"></div>

css:

[css] view plain copy

.left,.right{

position: absolute

width: 200px

height: 300px

background-color: yellow

}

.left{

left: 0

}

.right{

right: 0

}

.center{

margin: 0 210px

height: 300px

background-color: blue

}

该法布局的好处,三个div顺序可以任意改变。不足是 因为绝对定位,所以如果页面上还有其他内容,top的值需要小心处理,最好能够对css样式进行一个初始化,如果不对样式进行初始化,则两边和中间的值会对不齐。 另外,随着浏览器窗口缩小,小于200px的时候,会发生重叠。

在两个ul的外面再套上一个层,把这个层设为绝对定位的,两个ul则设为静态并且向左浮动的,就能实现你要的效果了:

<style>

*{

margin:0px

padding:0px

}

.box{

position:absolute

}

#ul1{

background:green

float:left

}

#ul2 {

background:blue

float:left

}

#ul2 li{

list-style:none

float:left

}

</style>

<div style="width:200pxheight:200pxbackground:redposition:relative">

<div class=box>

<ul id="ul1">

<li>aaa</li>

<li>aaa</li>

<li>aaa</li>

<li>aaa</li>

<li>aaa</li>

</ul>

<ul id="ul2">

<li>bbb</li>

<li>bbb</li>

</ul>

</div>

</div>