css和HTML布局小技巧
生活随笔
收集整理的這篇文章主要介紹了
css和HTML布局小技巧
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一:水平居中
? ? ? 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屬性,把子元素變成行內(nèi)框,display:inline-block;(子元素可以是行內(nèi)元素也可以是塊級(jí)元素)
第二種方法:給子元素添加margin:0 auto;屬性(子元素必須有寬度,而且必須是塊級(jí)元素);
?
第三種方法:利用絕對(duì)定位和相對(duì)定位實(shí)現(xiàn)
?
.parent{width:300px;height:200px;border:1px solid #000;position: relative;//設(shè)置相對(duì)定位以配合子元素的絕對(duì)定位}.child{width: 50px;height:50px;border:1px solid red;position: absolute;left:50%;margin-left: -25px;//元素寬度的一半}?
二,垂直居中
第一種方法:和上面一樣利用絕對(duì)定位
.parent{width:300px;height:200px;border:1px solid #000;position: relative;//設(shè)置相對(duì)定位以配合子元素的絕對(duì)定位}.child{width: 50px;height:50px;border:1px solid red;position: absolute;top:50%;margin-top: -25px;}第二種方法:
給parent增加 display:table-cell;vertical-align: middle;
?
轉(zhuǎn)載于:https://www.cnblogs.com/longailong/p/7338371.html
總結(jié)
以上是生活随笔為你收集整理的css和HTML布局小技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 洛谷P1402 酒店之王(二分图)
- 下一篇: 移动端适配与响应式布局