[英]Center div with text inside
I have a div element with following css and I need to center this inside parent container: 我有一个具有以下CSS的div元素,我需要在父容器内部居中:
<div id='download_confirm'>DOWNLOAD STARTED</div>
.download_confirm{
position:absolute;
top:0px;
left:0px;
padding:10px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
color:#fff;
background:#ccc;
}
How can I achieve that? 我该如何实现?
First, give position:relative
to you div's parent element. 首先,指定
position:relative
对于div的父元素。
1) - if you want this div to be centered horizontally and vertically, then: 1)-如果您希望该div在水平和垂直方向上居中,则:
.download_confirm{
position:absolute;
width:200px;
height: 90px;
top:50%;
left:50%;
padding:10px;
margin-top: -45px;
margin-left: -100px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
color:#fff;
background:#ccc;
}
. 。
2) - if you want your div to be centered only horizontally, then: 2)-如果您希望div仅水平居中,则:
.download_confirm{
position:absolute;
width:200px;
height: 90px;
padding:10px;
margin: 0 auto;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
color:#fff;
background:#ccc;
}
if there is no width or height,then this will be the solution, 如果没有宽度或高度,那么这将是解决方案,
This will position the div
with position:absolute
in relative
with the parent div
, 这将使
div
的position:absolute
relative
对于父级div
position:absolute
,
.download_confirm{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
padding:10px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
color:#fff;
background:#ccc;
}
<div class="download_confirm">DOWNLOAD STARTED</div>
and check this:Absolute Horizontal And Vertical Centering In CSS very useful. 并检查以下内容:CSS中的绝对水平和垂直居中非常有用。
You just need this, it's that simple, no need to know widths, heights, nothing:
您只需要这个,就这么简单,不需要知道宽度,高度,什么都不需要:
if you only want horizontail center then give your div a width and set left and right margins to auto. 如果只希望水平尾部居中,则为div设置宽度,并将左右边距设置为auto。 Lose the posistion, top and left css lines.
失去通透性,顶部和左侧的css线。
but if you want vertical and horizontal center i suggest javascript to get viewport size and then set left and top positions. 但是,如果您想垂直和水平居中,建议使用javascript获取视口大小,然后设置左和顶位置。 Easier solution is to use bootstrap or some other frameworks alert plugin.
较简单的解决方案是使用引导程序或其他框架的警报插件。
See: http://getbootstrap.com/index.html or http://jqueryui.com/ 请参阅: http : //getbootstrap.com/index.html或http://jqueryui.com/
.download_confirm{ .download_confirm {
width: 100px;
margin: 0px auto;
padding:10px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
color:#fff;
background:#ccc;
} }
使用#选择一个ID而不是一个表示类选择的句点,然后将width和margin-left和margin-right设置为auto
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.