css如何设置div居左 居中和居右

html-css019

css如何设置div居左 居中和居右,第1张

<style>

div {position:absolute width:200px height:400px}

div.left {left:0 background-color:red}

div.center {left:50% margin-left:-100px background-color:green}

div.right {right:0 background-color:blue}

</style>

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

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

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

CSS中的position property一共有四种:

postion: static

postion: relative

position: fixed

position: absolute

如果设置div为static postion, div的位置将不受top,right,left,button等变量的影响,而是按照正常的页面布局进行排版。例:

div.static {

        position: static

        border: 3px solid #8AC007

    }

如果设置div为relative position, 其变量的值将会使div的位置相对其正常(default)位置进行移动。例:

div.relative {

        position: relative

        left: 30px

        border: 3px solid #8AC007

    }

如果设置div为fixed position, div将会被固定在窗口的固定位置。也就是说无论你如何上下移动页面, div在屏幕上显示的位置始终不变。

div.fixed {

        position: fixed

        bottom: 0

        right: 0

        width: 300px

        border: 3px solid #8AC007

    }

如果设置div为absolute position, div将会相对于其最近的position ancestor定位。absolute position是可以随页面移动而移动在屏幕上的位置的。

div.absolute {

        position: absolute

        top: 80px

        right: 0

        width: 200px

        height: 100px

        border: 3px solid #8AC007

    }

以上CSS你可以放到自己的网页应用里试一下,区别就很明显了。

参考资料:http://www.w3schools.com/css/css_positioning.asp

右边的图片,也就是右边img标签要写在第二段文字的最前面,然后再为图片设置右对齐,再设置相当的左边距就能实现右边的效果。样式代码如下:

img {float:rightmargin-left:20px}

把图片放在第二段文字的最前面,复制以上样式即可实现。