猿问

CSS:<div>元素内的中心元素

CSS:<div>元素内的中心元素

要居中HTML元素,我可以使用CSS left: 50%;。但是,这使元素相对于整个窗口居中。

我有一个元素,它是元素的子<div>元素,并且我想相对于此父元素而<div>不是整个窗口居中显示该子元素。

我不想容器<div>所有的内容为中心,只是一个特定的孩子。

我怎样才能做到这一点?


九州编程
浏览 437回答 3
3回答

慕标5832272

设置text-align:center;为父div和margin:auto;子div。#parent {&nbsp; &nbsp; text-align:center;&nbsp; &nbsp; background-color:blue;&nbsp; &nbsp; height:400px;&nbsp; &nbsp; width:600px;}.block {&nbsp; &nbsp; height:100px;&nbsp; &nbsp; width:200px;&nbsp; &nbsp; text-align:left;}.center {&nbsp; &nbsp; margin:auto;&nbsp; &nbsp; background-color:green;}.left {&nbsp; &nbsp; margin:auto auto auto 0;&nbsp; &nbsp; background-color:red;}.right {&nbsp; &nbsp; margin:auto 0 auto auto;&nbsp; &nbsp; background-color:yellow;}<div id="parent">&nbsp; &nbsp; <div id="child1" class="block center">&nbsp; &nbsp; &nbsp; &nbsp; a block to align center and with text aligned left&nbsp; &nbsp; </div>&nbsp; &nbsp; <div id="child2" class="block left">&nbsp; &nbsp; &nbsp; &nbsp; a block to align left and with text aligned left&nbsp; &nbsp; </div>&nbsp; &nbsp; <div id="child3" class="block right">&nbsp; &nbsp; &nbsp; &nbsp; a block to align right and with text aligned left&nbsp; &nbsp; </div></div>这是一个几乎可以集中所有内容的好资源。http://howtocenterincss.com/
随时随地看视频慕课网APP
我要回答