CSS中如何让盒子自动占完其余所有宽度, 比如 <body> <div1> <div2

html-css07

CSS中如何让盒子自动占完其余所有宽度, 比如 <body> <div1> <div2,第1张

只用CSS是实现不了的,你要么用表格,左右定义宽度,中间自动,要么写JS来控制中间DIV宽度

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>无标题文档</title>

<script type="text/javascript" src="jquery.js"></script>

<style>

.div1{ width:100%height:25px}

.div2{ width:40pxheight:25pxfloat:leftborder:1px solid #777}

.div3{ float:leftborder:1px solid red}

.div4{ width:40pxheight:25pxfloat:rightborder:1px solid #777}

</style>

</head>

<body>

<div class="div1">

<div class="div2">

2

</div>

<div class="div3">3</div>

<div class="div4">4</div>

</div>

</body>

<script>

tmntH()//加载的时候执行一次

$(window).resize(function() {tmntH()})//浏览器窗口变化时执行

function tmntH()

{

var div3=$(".div1").width()-86+'px'//div3的宽度等于div1宽度-80-6(边框线)

//alert(div3)

$(".div3").css("width",div3)

}

</script>

</body>

</html>

css 默认盒子样式是 content-box, 宽高设定的是内容的宽高,设置边框可能会出现溢出的问题

可以通过设置 border-sizing:border-box

我更喜欢用border-box,因为border-box更灵活一点,举个例子,我在业务中遇到一个问题,我的商品详情页的一个盒子是高度自适应的,为146px,但是在ie8浏览器上显示为146.8px,如何解决,如果对盒子设置height:146px则会出现被撑高的情况,因为box-sizing默认为content-box,你给元素设置宽高,只是给元素内容设置宽高,你元素的总高度是heigtht + border + padding所以就会出现撑高,解决方法就是给当前的盒子设置box-sizing: border-box这样你设置高度为146px时,会默然将元素内容的高度进行相应减少来保证整体高度为146px,这个最大的好处就是你这个盒子有好几个,而且有不同的padding和border值,解决这个的最好的方法就是给盒子设置border-box