Html 您可以使用 display: table-cell 并具有固定的宽度/高度吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6977313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:56:50  来源:igfitidea点击:

Can you use display: table-cell and have a fixed width/height?

htmlcsscss-tables

提问by CodeWombat

I have the following:

我有以下几点:

CSS:

CSS:

.photo {
  overflow: hidden;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 100px;
  height: 100px;
}

HAML

反洗钱

.photo
  %img{:src => my_url}

See the jsFiddle here. The image I used to demonstrate is 150px by 80px.

这里查看 jsFiddle 。我用来演示的图像是 150 像素 x 80 像素。

I need to display the image inside the .photodiv and crop off any excess. The image needs to be centered vertically and horizontally. However, display:table-cellcauses the .photodiv to ignore my width and height settings. How can I get around this?

我需要在.photodiv内显示图像并裁剪掉多余的图像。图像需要垂直和水平居中。但是,display:table-cell导致.photodiv 忽略我的宽度和高度设置。我怎样才能解决这个问题?

采纳答案by MatTheCat

table-cellis not the only solution to vertical-align.

table-cell不是垂直对齐的唯一解决方案。

.photo {
    overflow: hidden;
    background: #c0c0c0;
    display:inline-block; /* or float:left; */
    text-align: center;
    width: 100px;
    height: 100px;
    line-height:97px;
}
.photo img {
    vertical-align:middle;
    max-width:100%;
    max-height:100%;
}

回答by general666

You can use display: table-cellbut the parent needs to have display: table-rowand the parent of the row should have display: table;

您可以使用,display: table-cell但父级需要具有display: table-row并且该行的父级应该具有display: table;

回答by locrizak

If you put an inner divit seems to work. Not sure why you need display:table-cellin the first place?

如果你放一个内部div它似乎工作。不知道为什么你display:table-cell首先需要?

http://jsfiddle.net/locrizak/5tawU/

http://jsfiddle.net/locrizak/5tawU/

Also, have you considered just putting a width on the image? This will cause the image's height to also resize accordingly.

另外,您是否考虑过仅在图像上放置宽度?这将导致图像的高度也相应地调整大小。