要居中一个HTML元素,我可以使用CSS左:50%;。但是,这使得元素相对于整个窗口居中。
我有一个元素,它是<div>元素的子元素,我想让子元素以<div>这个父元素居中,而不是整个窗口。
我不希望容器<div>的所有内容居中,只是一个特定的子。
要居中一个HTML元素,我可以使用CSS左:50%;。但是,这使得元素相对于整个窗口居中。
我有一个元素,它是<div>元素的子元素,我想让子元素以<div>这个父元素居中,而不是整个窗口。
我不希望容器<div>的所有内容居中,只是一个特定的子。
当前回答
text-align:中心;在父div应该做的把戏
其他回答
我相信现代的方法是在父容器中放置位置-项目:居中
一个例子可以在这里找到:https://1linelayouts.glitch.me
弯曲后,它显示文章
.container { 显示:flex; 颜色:蓝色; 背景颜色:黄色; justify-content:中心; } < div class = "容器" > < div > < / div元素> < / div > 如果你水平和垂直地设置元素中心。
.container { 显示:flex; 颜色:蓝色; 身高:100 px; 背景颜色:黄色; justify-content:中心; 对齐项目:中心; } < div class = "容器" > < div > < / div元素> < / div >
CSS
body{
text-align:center;
}
.divWrapper{
width:960px //Change it the to width of the parent you want
margin: 0 auto;
text-align:left;
}
HTML
<div class="divWrapper">Tada!!</div>
这应该使div居中
2016年HTML5 + CSS3方法
CSS
div#relative{
position:relative;
}
div#thisDiv{
position:absolute;
left:50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
}
HTML
<div id="relative">
<div id="thisDiv">Bla bla bla</div>
</div>
Fiddledlidle
https://jsfiddle.net/1z7m83dx/
有很多方法可以让元素居中,可以使用显示属性,位置,浮动,边距。但通常我更喜欢使用flexbox,因为它简单易用。我知道不同的人有不同的偏好,但这完全取决于开发人员的偏好和元素之间的关系。
.parent { 显示:块; } .sub-parent-1 { 显示:flex; justify-content:中心;/ /水平居中 对齐项目:中心;/ /垂直定心 } 身体< > < div class = "父" > < div class = " sub-parent-1”> < div class = " child-1 " >…< / div > < / div > < div class = " child-2 " >…< / div > < div class = " child-3 " >…< / div > < div class = " child-4 " >…< / div > < div class = " child-5 " >…< / div > < / div > 身体< / >
例如,我有一个文章div里面的主要内容div.. 在文章里面有一个图片,图片下面是一个按钮,样式如下:
.article {
width: whatever;
text-align: center;
float: whatever (in case you got more articles in a row);
margin: give it whatever margin you want;
} .article {
}
/*在文章里面,我想让图像居中*/
文章{
float: none;
margin: 0 auto;
padding: give it a padded ridge if you want;
}
/*现在,在同一article元素的这张图片下,应该有一个按钮,如阅读更多。当然,当它在响应式设计中时,你需要使用em或%
.button {
background: #whatever color:
padding: 4.3567%; /*Instead of fixed width*/
text-align: cente;
font: whatever;
max-width: 41.4166%;
float: none;
margin: 0 auto; /* You could make the zero into any margin you want on the top and bottom of this button.. Just notice the float: none property.. this wil solve most your issues, also check if maybe position and displaay might mess up your code..*/
}
祝你好运