css和HTML布局小技巧
生活随笔
收集整理的這篇文章主要介紹了
css和HTML布局小技巧
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:水平居中
? ? ? 1. 如下所示,讓child在parent中水平居中
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title><style>.parent{ width:300px; height:200px; border:1px solid #000; text-align: center; }.child{ width: 50px; height:50px; border:1px solid red; display: inline-block;}</style> </head> <body> <div class="parent"><div class="child"></div> </div> </body> </html>第一種方法:給父元素添加text-align:center屬性,把子元素變成行內框,display:inline-block;(子元素可以是行內元素也可以是塊級元素)
第二種方法:給子元素添加margin:0 auto;屬性(子元素必須有寬度,而且必須是塊級元素);
?
第三種方法:利用絕對定位和相對定位實現
?
.parent{width:300px;height:200px;border:1px solid #000;position: relative;//設置相對定位以配合子元素的絕對定位}.child{width: 50px;height:50px;border:1px solid red;position: absolute;left:50%;margin-left: -25px;//元素寬度的一半}?
二,垂直居中
第一種方法:和上面一樣利用絕對定位
.parent{width:300px;height:200px;border:1px solid #000;position: relative;//設置相對定位以配合子元素的絕對定位}.child{width: 50px;height:50px;border:1px solid red;position: absolute;top:50%;margin-top: -25px;}第二種方法:
給parent增加 display:table-cell;vertical-align: middle;
?
轉載于:https://www.cnblogs.com/longailong/p/7338371.html
總結
以上是生活随笔為你收集整理的css和HTML布局小技巧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷P1402 酒店之王(二分图)
- 下一篇: 2017年html5行业报告,云适配发布