Yii2 GridView无法设置列宽

use*_*695 12 php gridview yii2

这是我第一次使用Yii2 GridView Widget.我在stackoverflow上阅读了一些答案后尝试设置列的宽度,但它对我不起作用,如果列的宽度不同(特别是第一个),我会很喜欢它.

我已尝试直接使用'contentOptions'为第一列设置宽度,并使用外部CSS文件设置产品名称列.

有人可以告诉我是否有替代方案或者我做错了什么?

 <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn',
            'contentOptions' => ['style' => 'max-width:20px;'],
        ],

        [
            'format' => 'raw', 
            'label' => 'Image',
            'value' => function ($data) { 
                $url = $data->imgSrc;
                return Html::img($url, ['width' => '40px']);
            },
        ],

        [
            'attribute' => 'name',
            'format' => 'raw',
            'label' => 'Product name',
            'contentOptions' => function ($model, $key, $index, $column) {
                return ['class' => 'tbl_name'];
            },
        ],
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

sam*_*bua 16

如果要为单列设置宽度,可以使用headerOptions:

[
  'attribute' => 'attribute_name',
   'headerOptions' => ['style' => 'width:20%'],
],
Run Code Online (Sandbox Code Playgroud)


fre*_*esh 8

你必须这样设置:

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            [
                'attribute'=>'title',
                'contentOptions' => ['style' => 'width:200px; white-space: normal;'],
            ],
        ]
    ]
);
?>
Run Code Online (Sandbox Code Playgroud)

使用contentOptions,您可以为"title"列设置所有td的选项.在Site.css中,默认情况下将白色空间设置为nowrap.

.grid-view td {
    white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您的内容超过200像素,则col将按内容展开并忽略您的内容.


小智 8

首先添加选项

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'options' => [ 'style' => 'table-layout:fixed;' ],
Run Code Online (Sandbox Code Playgroud)

之后添加以下行

[
    'attribute' => 'news_description',
    'contentOptions' => [ 'style' => 'width: 25%;' ],
],
Run Code Online (Sandbox Code Playgroud)


Ros*_*nko 5

这可能是white-space css属性的结果,它会影响表格单元格的宽度,具体取决于其中的内容.在我的Yii2项目中,我有:

.grid-view td {
    white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)

这里提供的建议中没有人对我没用.但这很有用:

.grid-view td {
  white-space:pre-line; // or just 'normal'
}
Run Code Online (Sandbox Code Playgroud)


Chi*_*may 0

尝试一下Options

 [
        'class' => 'yii\grid\SerialColumn',
        'options' => ['style' => 'max-width:20px;'],
 ],
Run Code Online (Sandbox Code Playgroud)