CSS:一个< div>中的元素元件 [英] CSS: center element within a <div> element

查看:94
本文介绍了CSS:一个< div>中的元素元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使HTML元素居中,我可以使用CSS left:50%;

To center an HTML element I can use the CSS left: 50%;. However, this centers the element with respect to the whole window.

我有一个元素,它是< div> 元素,我想让这个父对象< div> 而不是整个窗口居中。

I have an element which is a child of a <div> element and I want to center the child with respect to this parent <div>, not the whole window.

我如何做?

EDIT :我不想要容器

EDIT: I do not want the container <div> to have all its content centered, just the one specific child.

推荐答案

>

设置text-align:center;到父div,和margin:auto;到子div。

Set text-align:center; to the parent div, and margin:auto; to the child div.

JsFiddle演示

HTML

<div id="parent">
    <div id="child1" class="block center">a block to align center and with text aligned left</div>
    <div id="child2" class="block left">a block to align left and with text aligned left</div>
    <div id="child3" class="block right">a block to align right and with text aligned left</div>
</div>

CSS

#parent {
    text-align:center;
    background-color:blue;
    height:400px;
    width:600px;
}
.block {
    height:100px;
    width:200px;
    text-align:left;
}
.center {
    margin:auto;
    background-color:green;
}
.left {
    margin:auto auto auto 0;
    background-color:red;
}
.right {
    margin:auto 0 auto auto;
    background-color:yellow;
}

UPDATE

这是一个很好的资源,主要以任何内容为中心。

http://howtocenterincss.com/

This a good resource to center mostly anything.
http://howtocenterincss.com/

这篇关于CSS:一个&lt; div&gt;中的元素元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆