首页 > 技术文章 > Div 不换行、垂直居中等样式

Extreme 2013-11-20 19:48 原文

1. Div内文本过长不换行

1.1 文本不换行 超出部分显示"..."

.style1

{

 float:left;

 white-space:nowrap;

 text-overflow:ellipsis;

 overflow: hidden;

 }

 

1.2 文本不换行 超出部分隐藏

.style2

 {

float: left;

 white-space:nowrap;

 overflow: hidden;

}

1.3文本不换行 超出时出现滚动条 拖动可查看全部内容

.style3

{

 float:left;

 white-space:nowrap;

 }

 

1.4 根据Div宽度自动显示隐藏

应用实例:界面大小变化时,Div宽度变化,文字则根据Div的宽度显示或隐藏

 

样式:

.Name

{

 

float:left;

display:block;

white-space:nowrap;

text-overflow:ellipsis;

-o-text-overflow:ellipsis;

overflow: hidden;

}

 

最大宽度控制:

 

$(function () {

    resize();

    $(window).resize(function () {

        resize();

    });

}

function resize() {

var Width = window.Width;

if (Width>0) {

      $('.Name').css({ "max-width": Width - 112 });//112是为左右相邻元素留出的固定宽度

      }  

}

 

2. Div不换行,自适应大小

2.1 多个div显示到1行的方法

除最右一个div外所有的div设置样式 float:left; 最右边一个样式设置可以 float:right;也可以 float:left;

 

2.2 页面缩小时,让排列在一行的3个div不换行

为中间的div固定宽度,当界面放大缩小时,动态调整左右两个div的宽度,使3个div占满整个页面,但不换行。

如果用百分比把3个div固定死,页面宽度缩小是还是会换行。要动态调整3个div的宽度:

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

<head>

    <title></title>

    <style>

        .left {

            float:left;

            overflow:hidden;

            background-color:yellow;

        }

        .center {

            float:left;

            background-color:pink;

            width:360px;

        }

        .right {

            float:left;

            overflow:hidden;

            background-color:blue;

        }

    </style>

    <script src="Scripts/jquery-1.7.1.min.js"></script>

    <script type="text/javascript">

       

        $(function () {

            resize();

            window.onresize = resize;

        });

       

        function resize() {

            var Width = $("#main").width();        //总宽度

            var centerWidth = $(".center").width();//中间div的宽度

            var lrWidth = Width - centerWidth;     //左右div的宽度总和

            if (lrWidth < 0)                                      

            {

                $(".left").hide();

                $(".right").hide();

            }//隐藏左右div

            else {

                $(".left").width(lrWidth / 2).show();

                $(".right").width(lrWidth / 2).show();

            }//设置宽度并显示左右div

        }

</script> 

 

</head>

<body>

    <div style="width:100%;" id="main">  

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

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

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

</div>

 

</body>

</html>

3. div垂直居中

如果是单行文字想垂直居中,只要保证div高和行高保持一致: 

css代码:

#div-a{

height:50px;

line-height:50px;

}

HTML代码:

<div id="div-a">

文字垂直居中

</div>

推荐阅读